/**
 * Import 工具通用接口（详见 docs/modules/robot-manager/14-import-export-tool-prd.md §7.1）
 *
 * M1 阶段：仅 PurchaseOrderImporter 一个 implementer，不抽 framework 共性。
 * M2 阶段：加 RobotUnitImporter 时从 2 个 implementer 提炼通用 Importer<T,U> 接口。
 *
 * 本文件先给类型定义（FieldMetadata / ValidationIssue / ExecuteResult），
 * 每个 importer 直接实现具体方法，不强制统一抽象。
 */
import type { Prisma, ImportBatchType } from '@prisma/client';

/** 字段元数据 — 用于模板生成 + 表头颜色 + Excel data validation + Sheet2 字段说明 */
export interface FieldMetadata {
  field: string;
  label: { zh: string; en: string };
  type: 'string' | 'number' | 'date' | 'enum' | 'uuid' | 'fk';
  required: boolean;
  /** 枚举值（type=enum 时） */
  enumValues?: string[];
  /** FK 引用（type=fk 时）；模板生成时**只导 label 不导 table/column 物理名**避免 schema 暴露 */
  fkRef?: { table: string; column: string };
  description?: { zh: string; en: string };
  // M2 待加：conditionalRequired（条件必填，RobotUnit startingStage 用）/ pii（payload mask 前的标记）。
  // M1 PO importer 无需求，先不引入避免接口形状提前固化。
  /** 模板示例数据（合成假数据，**禁从真实表 sample**） */
  example?: string;
}

/** 单行校验结果 */
export interface ValidationIssue {
  rowNo: number;
  field: string;
  /** SCREAMING_SNAKE i18n key（如 'IMPORT_FILE_INVALID'），前端按 `t.robotManager.errorCodes[code]` 渲染 */
  code: string;
  params: Record<string, string>;
  severity: 'ERROR' | 'WARNING';
  // ⚠️ 禁止存预渲染 message
}

/** importer.execute() 返回 — 支持一行扇出多 entity */
export interface ExecuteResult {
  rowResults: { rowNo: number; entityIds: string[] }[];
  sideEffects?: { recordCount?: number; notes?: string };
}

/** 解析阶段结果（parseExcel 返回，传给 importer） */
export interface ParsedRow<TInput = Record<string, unknown>> {
  rowNo: number;
  raw: Record<string, unknown>;
  /** 解析失败时 typed = null + parseIssues 含错误 */
  typed: TInput | null;
  parseIssues: ValidationIssue[];
}

/** Importer 通用接口（M1 PO 直接实现；M2 抽通用） */
export interface Importer<TInput> {
  readonly type: ImportBatchType;
  readonly fieldMetadata: FieldMetadata[];
  /** 把 Excel 一行原始 cell 值转成 typed input；同步解析（类型/必填初步检查） */
  parseRow(rawRow: Record<string, unknown>, rowNo: number): ParsedRow<TInput>;
  /** 批量 FK 校验（用 platform-master / robot-manager service 的 findByCodesIn） */
  validateReferences(rows: ParsedRow<TInput>[]): Promise<ValidationIssue[]>;
  /** 业务规则校验（quantity > 0 / 跨行 unique 等） */
  validateBusinessRules(rows: ParsedRow<TInput>[]): Promise<ValidationIssue[]>;
  /** 实际写库；在 prisma.$transaction 内调用；all-or-nothing 顶层语义 */
  execute(rows: TInput[], tx: Prisma.TransactionClient, userId: string, organizationId: string): Promise<ExecuteResult>;
}
