/**
 * Unified Excel batch-import workflow (v1).
 *
 * Staged by business dependency:
 *   students / rooms (基础档案) → checkins / transfers (关系)
 * Each stage is previewed, confirmed and committed separately.
 */

export const IMPORT_STEP_KEYS = ['students', 'rooms', 'checkins', 'transfers'] as const;
export type ImportStepKey = (typeof IMPORT_STEP_KEYS)[number];

export const IMPORT_STEP_ORDER: readonly ImportStepKey[] = [
  'students',
  'rooms',
  'checkins',
  'transfers',
];

export type CellValue = string | number | boolean | Date | null;

export type ImportRunSource = 'ai' | 'manual';

export type ImportRunStatus =
  | 'preparing'
  | 'ready'
  | 'committing'
  | 'committed'
  | 'failed'
  | 'expired';

export type ImportStepStatus =
  | 'pending'
  | 'ready'
  | 'committing'
  | 'committed'
  | 'failed'
  | 'skipped';

export type ImportRowStatus = 'pending' | 'valid' | 'error' | 'committed' | 'skipped';

export type ImportRowAction = 'create' | 'update' | 'skip';

/** field -> sheet header name */
export type ColumnMapping = Record<string, string>;

// aislop-ignore-next-line: duplicate-type-declaration -- 与前端 ImportWizard 的 API 契约保持一致
export interface ImportStageRequest {
  stepKey: ImportStepKey;
  /** 兼容旧调用：单个工作表名。 */
  sheet?: string;
  /** 一个阶段可包含多张工作表；与 sheet 二选一（sheets 优先）。 */
  sheets?: string[];
  headerRow?: number;
}

export interface ImportStageSuggestion {
  stepKey: ImportStepKey;
  mapping: ColumnMapping;
  matchedFields: number;
}

export interface ParsedImportFile {
  originalName: string;
  mimeType: string;
  size: number;
  buffer: Buffer;
}

export interface ImportRowDecision {
  rowId: number;
  action: ImportRowAction;
}

export interface StepPreviewRow {
  id: number;
  rowNumber: number;
  sheetName: string;
  raw: Record<string, CellValue>;
  fields: Record<string, CellValue>;
  action: ImportRowAction | null;
  status: ImportRowStatus;
  errors: string[];
}

export interface StepPreviewSummary {
  total: number;
  valid: number;
  error: number;
  create: number;
  update: number;
  skip: number;
}

export interface StepCommitReceipt {
  runId: string;
  stepKey: ImportStepKey;
  status: 'committed' | 'already_committed' | 'conflict';
  created: number;
  updated: number;
  skipped: number;
  failed: number;
  total: number;
  nextStepKey: ImportStepKey | null;
  runStatus: ImportRunStatus;
  message: string;
}

// aislop-ignore-next-line: duplicate-type-declaration -- 与前端 ImportWizard 的 API 契约保持一致
export interface ImportSheetMeta {
  name: string;
  headers: string[];
  rowCount: number;
  suggestedStepKey: ImportStepKey | null;
}

export interface ImportStepDetail {
  id: number;
  stepKey: ImportStepKey;
  label: string;
  sheets: string[];
  status: import('./entities/import-step.entity').ImportStep['status'];
  mapping: ColumnMapping;
  summary: StepPreviewSummary | null;
  committedAt: string | null;
}

export interface ImportRunDetail {
  id: string;
  fileName: string;
  source: ImportRunSource;
  status: import('./entities/import-run.entity').ImportRun['status'];
  currentStepKey: ImportStepKey | null;
  createdAt: string;
  sheets: ImportSheetMeta[];
  steps: ImportStepDetail[];
  settings: ImportRunSettings;
}

/** 用户确认后写入导入任务的策略与映射。 */
export interface ImportRunSettings {
  /** 按阶段字段 -> 表头 的确认映射。 */
  mapping?: Partial<Record<ImportStepKey, ColumnMapping>>;
  /** 学生校区归属（在检测到校区问题时由用户确认）。 */
  organization?: string | null;
  /** 已匹配记录是否更新；默认 true。 */
  updateExisting?: boolean;
  /** 文件内重复行策略：error 报错 / skip 跳过；默认 error。 */
  duplicatePolicy?: 'error' | 'skip';
  /** 关系表找不到学生/宿舍时是否跳过；默认 false。 */
  skipUnmatched?: boolean;
}

export interface StepPreviewResult {
  stepKey: ImportStepKey;
  sheetNames: string[];
  headers: string[];
  mapping: ColumnMapping;
  rows: StepPreviewRow[];
  summary: StepPreviewSummary;
}

export const IMPORT_ACTION_LABELS: Record<ImportRowAction, string> = {
  create: '新建',
  update: '更新',
  skip: '跳过',
};

/** Field alias tables used to auto-suggest column mappings. */
export const IMPORT_FIELD_ALIASES: Record<ImportStepKey, Record<string, string[]>> = {
  students: {
    name: ['姓名', '名字', '学生姓名', '学生名字'],
    studentNo: ['学号', '学生学号', '编号'],
    phone: ['手机号', '手机号码', '联系电话', '电话'],
    gender: ['性别'],
    idNumber: ['身份证', '身份证号', '身份证号码'],
    ethnicity: ['民族'],
    emergencyContact: ['紧急联系人'],
    emergencyPhone: ['紧急联系电话', '紧急电话'],
    organization: ['校区', '机构', '组织', '校区名称'],
    status: ['状态'],
  },
  rooms: {
    roomNumber: ['宿舍号', '房间号', '房号', '宿舍编号'],
    building: ['楼栋', '楼', '栋'],
    floor: ['楼层'],
    capacity: ['容量', '床位数', '人数'],
    roomType: ['房型', '房间类型', '宿舍类型'],
    rentalCategory: ['租期', '租期类型'],
    monthlyRate: ['月租', '月租金', '租金'],
  },
  checkins: {
    name: ['姓名', '学生姓名', '名字'],
    studentNo: ['学号', '学生学号'],
    phone: ['手机号', '手机号码', '电话'],
    roomNumber: ['宿舍号', '房间号', '房号'],
    checkInDate: ['入住日期', '入住时间', '日期'],
    stayType: ['住宿类型', '类型'],
  },
  transfers: {
    studentNo: ['学号', '学生学号'],
    phone: ['手机号', '手机号码'],
    oldRoom: ['原宿舍', '原房间', '原宿舍号', '旧宿舍', '旧房间'],
    newRoom: ['新宿舍', '新房间', '新宿舍号'],
    transferDate: ['换宿日期', '变更日期', '日期'],
    reason: ['原因', '备注', '换宿原因'],
  },
};

export const IMPORT_STEP_LABELS: Record<ImportStepKey, string> = {
  students: '学生档案',
  rooms: '宿舍档案',
  checkins: '入住记录',
  transfers: '换宿记录',
};

export const IMPORT_STEP_REQUIRED_FIELDS: Record<ImportStepKey, string[]> = {
  students: ['name'],
  rooms: ['roomNumber', 'capacity'],
  checkins: ['roomNumber', 'checkInDate'],
  transfers: ['oldRoom', 'newRoom', 'transferDate'],
};

export const IMPORT_STEP_IDENTITY_FIELDS: Record<ImportStepKey, string[]> = {
  students: ['studentNo', 'phone'],
  rooms: ['roomNumber'],
  checkins: ['studentNo', 'phone'],
  transfers: ['studentNo', 'phone'],
};
