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

// CS관리 저장 (saveas.do → mergeCSM + deleteCSP/mergeCSP + deleteCSW/mergeCSW)
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 client = await pool.connect();

  try {
    await client.query("BEGIN");

    let objId = String(body.objId || "").trim();
    const isNew = !objId;
    if (isNew) objId = createObjectId();

    // SERVICE_NO 자동 채번 (신규일 때만)
    let serviceNo = String(body.service_no || "").trim();
    if (!serviceNo) {
      const r = await client.query(
        `SELECT 'CSM'||TO_CHAR(NOW(),'yy')::VARCHAR||'-'||LPAD(nextval('seq_as_no')::VARCHAR,4,'0') AS no`
      );
      serviceNo = r.rows[0].no;
    }

    const status = body.status && body.status !== "" ? body.status : "0000100";

    // MERGE CSM
    await client.query(
      `INSERT INTO customer_service_mgmt (
         objid, service_no, product, contract_objid, cs_category, warranty,
         manager_id, act_date, category_h, category_m, category_l, title,
         before_contents, after_contents, writer, regdate, status,
         total_sup_price, total_work_day, total_work_person, total_work_day_m,
         total_labor_cost, total_expenses
       ) VALUES ($1,$2,CASE WHEN $3='' THEN NULL ELSE $3 END,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,now(),$16,$17,$18,$19,$20,$21,$22)
       ON CONFLICT (objid) DO UPDATE SET
         service_no=EXCLUDED.service_no,
         product=EXCLUDED.product,
         contract_objid=EXCLUDED.contract_objid,
         cs_category=EXCLUDED.cs_category,
         warranty=EXCLUDED.warranty,
         manager_id=EXCLUDED.manager_id,
         act_date=EXCLUDED.act_date,
         category_h=EXCLUDED.category_h,
         category_m=EXCLUDED.category_m,
         category_l=EXCLUDED.category_l,
         title=EXCLUDED.title,
         before_contents=EXCLUDED.before_contents,
         after_contents=EXCLUDED.after_contents,
         writer=EXCLUDED.writer,
         regdate=now(),
         status=EXCLUDED.status,
         total_sup_price=EXCLUDED.total_sup_price,
         total_work_day=EXCLUDED.total_work_day,
         total_work_person=EXCLUDED.total_work_person,
         total_work_day_m=EXCLUDED.total_work_day_m,
         total_labor_cost=EXCLUDED.total_labor_cost,
         total_expenses=EXCLUDED.total_expenses`,
      [
        objId,
        serviceNo,
        body.product || "",
        body.contract_objid || "",
        body.cs_category || "",
        body.warranty || "",
        body.manager_id || "",
        body.act_date || "",
        body.category_h || "",
        body.category_m || "",
        body.category_l || "",
        body.title || "",
        body.before_contents || "",
        body.after_contents || "",
        body.writer || user.userId,
        status,
        String(body.TOTAL_SUP_PRICE || body.total_sup_price || "0").replace(/,/g, ""),
        String(body.TOTAL_WORK_DAY || body.total_work_day || "0").replace(/,/g, ""),
        String(body.TOTAL_WORK_PERSON || body.total_work_person || "0").replace(/,/g, ""),
        String(body.TOTAL_WORK_DAY_M || body.total_work_day_m || "0").replace(/,/g, ""),
        String(body.TOTAL_LABOR_COST || body.total_labor_cost || "0").replace(/,/g, ""),
        String(body.TOTAL_EXPENSES || body.total_expenses || "0").replace(/,/g, ""),
      ]
    );

    // CSP: 전체 삭제 후 재삽입
    await client.query(`DELETE FROM customer_service_part WHERE parent_objid = $1`, [objId]);
    const parts: Array<Record<string, unknown>> = Array.isArray(body.parts) ? body.parts : [];
    for (const p of parts) {
      const partObjId = String(p.OBJID || "").trim() || createObjectId();
      await client.query(
        `INSERT INTO customer_service_part
           (objid, parent_objid, part_no, part_name, spec, qty, cur_qty, price, sup_price)
         VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)`,
        [
          partObjId,
          objId,
          String(p.PART_NO || ""),
          String(p.PART_NAME || ""),
          String(p.SPEC || ""),
          String(p.QTY || "0").replace(/,/g, ""),
          String(p.CUR_QTY || "0").replace(/,/g, ""),
          String(p.PRICE || "0").replace(/,/g, ""),
          String(p.SUP_PRICE || "0").replace(/,/g, ""),
        ]
      );
    }

    // CSW: 전체 삭제 후 재삽입
    await client.query(`DELETE FROM customer_service_workingtime WHERE parent_objid = $1`, [objId]);
    const works: Array<Record<string, unknown>> = Array.isArray(body.works) ? body.works : [];
    for (const w of works) {
      const workObjId = String(w.OBJID || "").trim() || createObjectId();
      await client.query(
        `INSERT INTO customer_service_workingtime
           (objid, parent_objid, supply_objid, form_date, to_date, work_day, work_person, work_day_m, labor_cost, expenses)
         VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`,
        [
          workObjId,
          objId,
          String(w.SUPPLY_OBJID || ""),
          String(w.FORM_DATE || ""),
          String(w.TO_DATE || ""),
          String(w.WORK_DAY || "0").replace(/,/g, ""),
          String(w.WORK_PERSON || "0").replace(/,/g, ""),
          String(w.WORK_DAY_M || "0").replace(/,/g, ""),
          String(w.LABOR_COST || "0").replace(/,/g, ""),
          String(w.EXPENSES || "0").replace(/,/g, ""),
        ]
      );
    }

    await client.query("COMMIT");
    return NextResponse.json({
      success: true,
      message: isNew ? "등록되었습니다." : "수정되었습니다.",
      objId,
      serviceNo,
    });
  } catch (e) {
    await client.query("ROLLBACK");
    console.error("CS save:", e);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
  } finally {
    client.release();
  }
}
