// 매입 발주서 라인 추가/수정/삭제 — 관리자 전용. OPEN/REQUESTED 상태만.
import { NextRequest, NextResponse } from "next/server";
import { pool } from "@/lib/db";
import { createObjectId } from "@/lib/utils";
import { requireMomoAdmin } from "@/lib/momo-guard";

interface LineInput {
  objid?: string;
  itemObjid?: string;
  qty: number;
  costPrice: number;
  delete?: boolean;
}

export async function POST(req: NextRequest) {
  const g = await requireMomoAdmin();
  if (g instanceof NextResponse) return g;

  const body = await req.json().catch(() => ({}));
  const { procObjid, lines } = body as { procObjid?: string; lines?: LineInput[] };
  if (!procObjid || !Array.isArray(lines)) {
    return NextResponse.json({ success: false, message: "잘못된 요청입니다." }, { status: 400 });
  }

  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    const procRes = await client.query(
      `SELECT status FROM momo_procurements WHERE objid = $1 FOR UPDATE`,
      [procObjid]
    );
    if (procRes.rowCount === 0) {
      await client.query("ROLLBACK");
      return NextResponse.json({ success: false, message: "발주서를 찾을 수 없습니다." }, { status: 404 });
    }
    const status = procRes.rows[0].status;
    // 입금완료(PAID)/취소(CANCELLED) 외 모든 상태에서 수정 허용
    if (status === "PAID" || status === "CANCELLED") {
      await client.query("ROLLBACK");
      return NextResponse.json({ success: false, message: "입금완료/취소 상태는 수정할 수 없습니다." }, { status: 400 });
    }

    for (const ln of lines) {
      const qty = Number(ln.qty) || 0;
      const cost = Math.round(Number(ln.costPrice) || 0);
      const total = Math.round(cost * qty);

      if (ln.delete && ln.objid) {
        await client.query(`DELETE FROM momo_procurement_items WHERE objid = $1 AND proc_objid = $2`, [ln.objid, procObjid]);
        continue;
      }
      if (qty <= 0 || cost < 0) {
        await client.query("ROLLBACK");
        return NextResponse.json({ success: false, message: "수량/단가 형식 오류" }, { status: 400 });
      }
      if (ln.objid) {
        await client.query(
          `UPDATE momo_procurement_items SET qty=$2, cost_price=$3, total_amount=$4 WHERE objid=$1`,
          [ln.objid, qty, cost, total]
        );
      } else if (ln.itemObjid) {
        // 중복 체크: 같은 procObjid + itemObjid 가 이미 있으면 수량/단가만 갱신
        const dup = await client.query(
          `SELECT objid, qty FROM momo_procurement_items WHERE proc_objid=$1 AND item_objid=$2 LIMIT 1`,
          [procObjid, ln.itemObjid]
        );
        if (dup.rowCount && dup.rowCount > 0) {
          const existObjid = dup.rows[0].objid;
          const newQty = Number(dup.rows[0].qty) + qty;
          const newTotal = Math.round(cost * newQty);
          await client.query(
            `UPDATE momo_procurement_items SET qty=$2, cost_price=$3, total_amount=$4 WHERE objid=$1`,
            [existObjid, newQty, cost, newTotal]
          );
        } else {
          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, cost, qty, total]
          );
        }
      }
    }

    // 합계 재집계
    const sum = await client.query(
      `SELECT COALESCE(SUM(total_amount), 0) AS total FROM momo_procurement_items WHERE proc_objid = $1`,
      [procObjid]
    );
    await client.query(
      `UPDATE momo_procurements SET total_amount = $2 WHERE objid = $1`,
      [procObjid, Number(sum.rows[0].total)]
    );

    await client.query("COMMIT");
    return NextResponse.json({ success: true });
  } catch (err) {
    await client.query("ROLLBACK");
    console.error("[procurements/lines/save]", err);
    const msg = err instanceof Error ? err.message : "라인 저장 오류";
    return NextResponse.json({ success: false, message: msg }, { status: 500 });
  } finally {
    client.release();
  }
}
