import { NextRequest, NextResponse } from "next/server";
import { pool } from "@/lib/db";
import { getSession } from "@/lib/session";
import { createObjectId } from "@/lib/utils";

interface PartRow {
  part_no?: string;
  part_name?: string;
  qty?: string;
  material?: string;
  spec?: string;
  post_processing?: string;
  maker?: string;
  part_type?: string;
  remark?: string;
}

// PART 엑셀 업로드 저장 (partMng.partUploadSave 대응 단순화)
// - 파싱된 행들을 part_mng에 일괄 INSERT (status='create', is_last='Y')
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const body = await request.json();
  const parts: PartRow[] = Array.isArray(body.parts) ? body.parts : [];
  if (parts.length === 0) {
    return NextResponse.json({ success: false, message: "저장할 데이터가 없습니다." }, { status: 400 });
  }

  // 품번 중복 체크 (문서 내)
  const seen = new Set<string>();
  const dups: string[] = [];
  parts.forEach((p) => {
    const n = String(p.part_no || "").trim();
    if (!n) return;
    if (seen.has(n)) dups.push(n);
    else seen.add(n);
  });
  if (dups.length > 0) {
    return NextResponse.json({
      success: false,
      message: `문서내 중복 품번: ${Array.from(new Set(dups)).join(", ")}`,
    }, { status: 400 });
  }

  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    let inserted = 0;
    for (let i = 0; i < parts.length; i++) {
      const p = parts[i];
      const partNo = String(p.part_no || "").trim();
      const partName = String(p.part_name || "").trim();
      if (!partNo || !partName) continue;

      await client.query(
        `INSERT INTO part_mng (objid, part_no, part_name, qty, material, spec,
           post_processing, maker, part_type, remark,
           status, revision, is_last, writer, reg_date, excel_upload_seq)
         VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,'create','0','Y',$11,now(),$12)`,
        [
          createObjectId(), partNo, partName,
          String(p.qty || ""), String(p.material || ""), String(p.spec || ""),
          String(p.post_processing || ""), String(p.maker || ""),
          String(p.part_type || ""), String(p.remark || ""),
          user.userId, String(i + 1),
        ],
      );
      inserted++;
    }
    await client.query("COMMIT");
    return NextResponse.json({ success: true, message: `${inserted}건이 등록되었습니다.` });
  } catch (e) {
    await client.query("ROLLBACK");
    console.error("Part excel save:", e);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
  } finally {
    client.release();
  }
}
