// 발주 품목(ITEM) 라인 수량 변경/삭제 — 본인 또는 관리자, REQUESTED 상태에서만.
// 단가는 변경 불가 (momo_items.unit_price 기준 그대로).
// 변경 후 momo_orders 합계 자동 재집계.
import { NextRequest, NextResponse } from "next/server";
import { pool } from "@/lib/db";
import { requireMomoUser } from "@/lib/momo-guard";
import { calcLine } from "@/lib/momo-pricing";

interface LineUpdate {
  objid: string;        // 라인 OBJID
  qty?: number;         // 새 수량 (undefined 면 변경 안 함)
  delete?: boolean;     // true 면 삭제
}

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?: LineUpdate[] };
  if (!orderObjid || !Array.isArray(lines) || lines.length === 0) {
    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 와 일치하면 OK
    // (momo 가입자는 user.objid, FITO 사용자는 user.userId 가 customer_objid 로 들어감)
    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)/취소 전까지 모두 (REQUESTED / SHIPPED 등)
    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 });
      }
    }

    for (const ln of lines) {
      // 라인 조회 + ITEM 종류 검증
      const lineRes = await client.query(
        `SELECT OI.objid, OI.item_objid, OI.unit_price, OI.qty, OI.is_tax_free,
                COALESCE(OI.kind,'ITEM') AS kind,
                I.item_name, I.max_order_qty,
                COALESCE((
                  SELECT SUM(S.qty) FROM momo_stocks S
                  JOIN momo_warehouses W ON S.wh_objid = W.objid
                  WHERE S.item_objid = OI.item_objid AND COALESCE(W.is_del,'N') != 'Y'
                ), 0) AS stock_qty
         FROM momo_order_items OI
         LEFT JOIN momo_items I ON I.objid = OI.item_objid
         WHERE OI.objid = $1 AND OI.order_objid = $2`,
        [ln.objid, orderObjid]
      );
      if (lineRes.rowCount === 0) continue;
      const cur = lineRes.rows[0];
      if (cur.kind !== "ITEM") {
        await client.query("ROLLBACK");
        return NextResponse.json({ success: false, message: "택배/용차 라인은 이 화면에서 수정할 수 없습니다." }, { status: 400 });
      }

      if (ln.delete) {
        await client.query(`DELETE FROM momo_order_items WHERE objid = $1`, [ln.objid]);
        continue;
      }

      const newQty = Number(ln.qty);
      if (!Number.isFinite(newQty) || newQty <= 0) {
        await client.query("ROLLBACK");
        return NextResponse.json({ success: false, message: "수량은 1 이상이어야 합니다." }, { status: 400 });
      }

      // 재고 / 한도 검증 (관리자가 아니고 unlimited_qty 권한 없으면)
      if (!isAdmin) {
        const stock = Number(cur.stock_qty);
        if (newQty > stock) {
          await client.query("ROLLBACK");
          return NextResponse.json({ success: false, message: `${cur.item_name} — 재고(${stock})를 초과할 수 없습니다.` }, { status: 400 });
        }
        const u = await client.query(
          `SELECT COALESCE(unlimited_qty,'N') AS u FROM user_info WHERE user_id = $1`,
          [r.user.objid]
        );
        const unlimited = u.rows[0]?.u === "Y";
        if (!unlimited) {
          const maxQ = cur.max_order_qty == null ? 0 : Number(cur.max_order_qty);
          if (maxQ > 0 && newQty > maxQ) {
            await client.query("ROLLBACK");
            return NextResponse.json({ success: false, message: `${cur.item_name} — 1회 발주 한도(${maxQ}) 초과` }, { status: 400 });
          }
        }
      }

      const isFree = cur.is_tax_free === "Y";
      const calc = calcLine({ unitPrice: Number(cur.unit_price), qty: newQty, isTaxFree: isFree });
      await client.query(
        `UPDATE momo_order_items SET
           qty = $2,
           supply_amount = $3,
           vat_amount = $4,
           total_amount = $5
         WHERE objid = $1`,
        [ln.objid, newQty, calc.supplyAmount, calc.vatAmount, calc.totalAmount]
      );
    }

    // 합계 재집계
    const sum = 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 = sum.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/items/update]", err);
    const msg = err instanceof Error ? err.message : "수정 오류";
    return NextResponse.json({ success: false, message: msg }, { status: 500 });
  } finally {
    client.release();
  }
}
