import { NextRequest, NextResponse } from "next/server";
import { pool, queryOne } from "@/lib/db";
import { createObjectId } from "@/lib/utils";
import { requireMomoAdmin } from "@/lib/momo-guard";

interface Line { itemObjid: string; qty: number; costPrice: number }

export async function POST(req: NextRequest) {
  const g = await requireMomoAdmin();
  if (g instanceof NextResponse) return g;
  const adminId = g.user.objid || g.user.userId;

  const { vendorObjid, procDate, lines, memo } = await req.json() as {
    vendorObjid?: string; procDate?: string; lines: Line[]; memo?: string;
  };
  if (!Array.isArray(lines) || lines.length === 0) {
    return NextResponse.json({ success: false, message: "발주 라인을 입력하세요." }, { status: 400 });
  }

  const procObjid = createObjectId();
  const procNo = await genProcNo();
  let total = 0;
  for (const ln of lines) total += Math.round(Number(ln.costPrice) * Number(ln.qty));

  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    await client.query(
      `INSERT INTO momo_procurements (objid, proc_no, vendor_objid, proc_date, status, total_amount, memo, regdate)
       VALUES ($1,$2,$3,COALESCE($4::date, CURRENT_DATE),'OPEN',$5,$6,NOW())`,
      [procObjid, procNo, vendorObjid ?? null, procDate ?? null, total, memo ?? null]
    );
    let seq = 0;
    for (const ln of lines) {
      seq++;
      const lineTotal = Math.round(Number(ln.costPrice) * Number(ln.qty));
      await client.query(
        `INSERT INTO momo_procurement_items (objid, proc_objid, item_objid, cost_price, qty, total_amount, received_qty, received_normal, received_defect)
         VALUES ($1,$2,$3,$4,$5,$6,0,0,0)`,
        [createObjectId(), procObjid, ln.itemObjid, ln.costPrice, ln.qty, lineTotal]
      );
    }
    await client.query("COMMIT");
    return NextResponse.json({ success: true, objId: procObjid, procNo });
  } catch (err) {
    await client.query("ROLLBACK");
    console.error("[procurement/save]", err);
    return NextResponse.json({ success: false, message: "발주 저장 오류" }, { status: 500 });
  } finally {
    client.release();
  }
}

async function genProcNo(): Promise<string> {
  const today = new Date();
  const ymd = `${today.getFullYear()}${String(today.getMonth() + 1).padStart(2, "0")}${String(today.getDate()).padStart(2, "0")}`;
  const prefix = `PRC-${ymd}-`;
  const row = await queryOne<{ MAX_NO: string }>(
    `SELECT COALESCE(MAX(proc_no), '') AS "MAX_NO" FROM momo_procurements WHERE proc_no LIKE $1 || '%'`,
    [prefix]
  );
  const lastNum = row?.MAX_NO ? Number(row.MAX_NO.replace(prefix, "")) || 0 : 0;
  return prefix + String(lastNum + 1).padStart(4, "0");
}
