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

// 원본: /salesMng/receiptSalesRequestInfo.do — sales_request_master.status='reception'
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const { objIds } = await request.json();
  if (!Array.isArray(objIds) || objIds.length === 0) {
    return NextResponse.json({ success: false, message: "접수할 항목을 선택하세요." });
  }

  const today = new Date().toISOString().slice(0, 10);
  const client = await pool.connect();
  try {
    await client.query("BEGIN");
    for (const objId of objIds) {
      await client.query(
        `UPDATE sales_request_master
            SET status = 'reception',
                receipt_date = $1,
                receipt_user_id = $2
          WHERE objid::text = $3`,
        [today, user.userId, String(objId)],
      );
    }
    await client.query("COMMIT");
    return NextResponse.json({ success: true, message: `${objIds.length}건 접수되었습니다.` });
  } catch (e) {
    await client.query("ROLLBACK");
    console.error("purchase/request receipt:", e);
    return NextResponse.json({ success: false, message: "접수 중 오류가 발생했습니다." }, { status: 500 });
  } finally {
    client.release();
  }
}
