// 발주 거래명세표에서 택배(DELIVERY)/용차(CHARTER) 라인 추가/수정/삭제
// REQUESTED 상태에서만 가능. 본인 또는 관리자.
// ITEM 라인은 이 엔드포인트로 변경 불가 (별도 흐름 필요).
import { NextRequest, NextResponse } from "next/server";
import { pool } from "@/lib/db";
import { createObjectId } from "@/lib/utils";
import { requireMomoUser } from "@/lib/momo-guard";
import { calcLine } from "@/lib/momo-pricing";

interface ExtraLineInput {
  objid?: string;        // 기존 라인 수정/삭제 시
  kind: "DELIVERY" | "CHARTER";
  label?: string;
  unitPrice: number;
  qty: number;
  delete?: boolean;
}

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

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

  const isAdmin = r.user.isAdmin || r.user.role === "ADMIN" || r.user.userType === "A";

  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    const orderRes = await client.query(
      `SELECT customer_objid, status FROM momo_orders WHERE objid = $1 FOR UPDATE`,
      [orderObjid]
    );
    if (orderRes.rowCount === 0) {
      await client.query("ROLLBACK");
      return NextResponse.json({ success: false, message: "발주를 찾을 수 없습니다." }, { status: 404 });
    }
    const order = orderRes.rows[0];
    // 본인 발주 매칭: customer_objid 가 user.objid 또는 user.userId 와 일치
    const userOwn = r.user.objid ?? r.user.userId;
    if (!isAdmin && order.customer_objid !== userOwn && order.customer_objid !== r.user.userId) {
      await client.query("ROLLBACK");
      return NextResponse.json({ success: false, message: "권한이 없습니다." }, { status: 403 });
    }
    // USER: REQUESTED 만, ADMIN: 입금완료(PAID)/취소 전까지 모두
    if (isAdmin) {
      if (order.status === "PAID" || order.status === "CANCELED") {
        await client.query("ROLLBACK");
        return NextResponse.json({ success: false, message: "입금완료 또는 취소된 발주는 수정할 수 없습니다." }, { status: 400 });
      }
    } else if (order.status !== "REQUESTED") {
      await client.query("ROLLBACK");
      return NextResponse.json({ success: false, message: "출고 요청 상태에서만 수정할 수 있습니다." }, { status: 400 });
    }

    // 다음 seq (현재 최대 + 1)
    const seqRes = await client.query(
      `SELECT COALESCE(MAX(seq), 0) AS m FROM momo_order_items WHERE order_objid = $1`,
      [orderObjid]
    );
    let nextSeq = Number(seqRes.rows[0]?.m ?? 0) + 1;

    for (const ln of lines) {
      if (ln.kind !== "DELIVERY" && ln.kind !== "CHARTER") {
        await client.query("ROLLBACK");
        return NextResponse.json({ success: false, message: "라인 종류가 올바르지 않습니다." }, { status: 400 });
      }

      if (ln.delete && ln.objid) {
        // 삭제 — ITEM 라인은 보호
        await client.query(
          `DELETE FROM momo_order_items
             WHERE objid = $1 AND order_objid = $2 AND kind IN ('DELIVERY','CHARTER')`,
          [ln.objid, orderObjid]
        );
        continue;
      }

      const unitPrice = Math.round(Number(ln.unitPrice) || 0);
      const qty = Number(ln.qty) || 0;
      if (unitPrice < 0 || qty <= 0) {
        await client.query("ROLLBACK");
        return NextResponse.json({ success: false, message: "단가/수량 형식이 올바르지 않습니다." }, { status: 400 });
      }
      const calc = calcLine({ unitPrice, qty, isTaxFree: false });
      const label = ln.label?.trim() || (ln.kind === "DELIVERY" ? "택배비" : "용차비");

      if (ln.objid) {
        // 수정
        await client.query(
          `UPDATE momo_order_items SET
             item_name_snap = $2,
             unit_price     = $3,
             qty            = $4,
             supply_amount  = $5,
             vat_amount     = $6,
             total_amount   = $7,
             kind           = $8,
             extra_label    = $2
           WHERE objid = $1 AND kind IN ('DELIVERY','CHARTER')`,
          [ln.objid, label, unitPrice, qty,
           calc.supplyAmount, calc.vatAmount, calc.totalAmount, ln.kind]
        );
      } else {
        // 신규
        await client.query(
          `INSERT INTO momo_order_items (
             objid, order_objid, item_objid, item_name_snap, unit_price, qty,
             is_tax_free, supply_amount, vat_amount, total_amount, seq, kind, extra_label
           ) VALUES ($1, $2, NULL, $3, $4, $5, 'N', $6, $7, $8, $9, $10, $3)`,
          [createObjectId(), orderObjid, label, unitPrice, qty,
           calc.supplyAmount, calc.vatAmount, calc.totalAmount, nextSeq, ln.kind]
        );
        nextSeq++;
      }
    }

    // 전체 재집계
    const sumRes = await client.query(
      `SELECT
         COALESCE(SUM(supply_amount), 0) AS supply,
         COALESCE(SUM(vat_amount), 0)    AS vat,
         COALESCE(SUM(total_amount), 0)  AS total,
         COALESCE(SUM(CASE WHEN is_tax_free='Y' THEN supply_amount ELSE 0 END), 0) AS taxfree,
         COALESCE(SUM(CASE WHEN is_tax_free='N' THEN supply_amount ELSE 0 END), 0) AS taxable,
         COALESCE(SUM(CASE WHEN kind='DELIVERY' THEN total_amount ELSE 0 END), 0) AS delivery,
         COALESCE(SUM(CASE WHEN kind='CHARTER'  THEN total_amount ELSE 0 END), 0) AS charter
       FROM momo_order_items WHERE order_objid = $1`,
      [orderObjid]
    );
    const t = sumRes.rows[0];
    await client.query(
      `UPDATE momo_orders SET
         total_supply   = $2,
         total_vat      = $3,
         total_amount   = $4,
         total_taxfree  = $5,
         total_taxable  = $6,
         total_delivery = $7,
         total_charter  = $8,
         update_date    = NOW(),
         update_id      = $9
       WHERE objid = $1`,
      [orderObjid, t.supply, t.vat, t.total, t.taxfree, t.taxable, t.delivery, t.charter,
       r.user.objid || r.user.userId]
    );

    await client.query("COMMIT");
    return NextResponse.json({ success: true });
  } catch (err) {
    await client.query("ROLLBACK");
    console.error("[orders/lines/save]", err);
    const msg = err instanceof Error ? err.message : "라인 저장 중 오류가 발생했습니다.";
    // PG 컬럼 없음(undefined column 42703) — 마이그레이션 미적용 케이스
    const hint = /column .* does not exist|undefined column|42703/i.test(msg)
      ? " · DB 마이그레이션 010(kind/extra_label/total_delivery/total_charter)이 적용되지 않은 것 같습니다."
      : "";
    return NextResponse.json({ success: false, message: msg + hint }, { status: 500 });
  } finally {
    client.release();
  }
}
