import {
  toProcurementMaterialInsert,
  type ProcurementMaterialInsertLike,
} from "../standardization/document-extraction-contract.ts";
import {
  extractMaterialsFromOriginalFile,
  type DocumentMaterialExtractionResult,
} from "../standardization/document-extraction-llm.ts";
import { supabase } from "./db.ts";

export interface ExtractAndInsertMaterialsParams {
  fileBuffer: Buffer;
  mimeType?: string | null;
  batchId: string;
  sourceFileId: string;
  sourceFileName: string;
  createdBy?: string;
  extractMaterials?: typeof extractMaterialsFromOriginalFile;
  db?: Pick<typeof supabase, "from">;
}

export interface ExtractAndInsertMaterialsResult {
  success: true;
  materials: unknown[];
  extraction_summary: string;
  summary: string;
  warnings: string[];
  extraction_model: string;
  extraction_provider: string;
}

export async function extractAndInsertMaterialsFromUploadedFile(
  params: ExtractAndInsertMaterialsParams,
): Promise<ExtractAndInsertMaterialsResult> {
  const extractMaterials = params.extractMaterials ?? extractMaterialsFromOriginalFile;
  const db = params.db ?? supabase;
  const extraction: DocumentMaterialExtractionResult = await extractMaterials({
    fileBuffer: params.fileBuffer,
    mimeType: params.mimeType,
    batchId: params.batchId,
    sourceFileName: params.sourceFileName,
  });

  const rows: ProcurementMaterialInsertLike[] = extraction.items.map((item) =>
    toProcurementMaterialInsert(item, {
      batchId: params.batchId,
      sourceFile: params.sourceFileName,
      sourceFileId: params.sourceFileId,
      createdBy: params.createdBy,
    }),
  );

  const { data, error } = await db
    .from("procurement_materials")
    .insert(rows)
    .select("*");

  if (error) {
    throw new Error(`[procurement_materials] 写入文档识别物料失败: ${error.message}`);
  }

  return {
    success: true,
    materials: data ?? [],
    extraction_summary: extraction.summary,
    summary: extraction.summary,
    warnings: extraction.warnings,
    extraction_model: extraction.model,
    extraction_provider: extraction.provider,
  };
}
