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

// 검사 저장 (inspection_mgmt UPSERT + 삭제)
// body: { parentObjid, rows: [{OBJID, UNIT_CODE, INTERNAL_INSPECTION_DATE, INTERNAL_INSPECTION_RESULT, INTERNAL_INSPECTION_ID}], deleteIds: string[] }
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const body = await request.json();
  const parentObjid = String(body.parentObjid || "");
  const rows: Array<Record<string, unknown>> = Array.isArray(body.rows) ? body.rows : [];
  const deleteIds: string[] = Array.isArray(body.deleteIds) ? body.deleteIds.map(String).filter(Boolean) : [];

  if (!parentObjid) return NextResponse.json({ success: false, message: "parentObjid 누락" }, { status: 400 });

  try {
    for (const id of deleteIds) {
      await execute(`DELETE FROM inspection_mgmt WHERE objid = $1`, [id]);
      // 첨부파일도 제거
      await execute(
        `UPDATE attach_file_info SET status = 'inactive'
           WHERE target_objid = $1 AND doc_type = 'INSPECTION_CHECKLIST_FILE'`,
        [id],
      );
    }

    for (const r of rows) {
      const objId = String(r.OBJID || "");
      if (!objId) continue;
      await execute(
        `INSERT INTO inspection_mgmt
           (objid, parent_objid, unit_code,
            internal_inspection_date, internal_inspection_result, internal_inspection_id,
            regdate, writer)
         VALUES ($1, $2, $3, $4, $5, $6, NOW(), $7)
         ON CONFLICT (objid) DO UPDATE SET
           parent_objid = EXCLUDED.parent_objid,
           unit_code = EXCLUDED.unit_code,
           internal_inspection_date = EXCLUDED.internal_inspection_date,
           internal_inspection_result = EXCLUDED.internal_inspection_result,
           internal_inspection_id = EXCLUDED.internal_inspection_id`,
        [
          objId,
          parentObjid,
          String(r.UNIT_CODE || ""),
          String(r.INTERNAL_INSPECTION_DATE || ""),
          String(r.INTERNAL_INSPECTION_RESULT || ""),
          String(r.INTERNAL_INSPECTION_ID || ""),
          user.userId,
        ],
      );
    }
    return NextResponse.json({ success: true, message: "저장되었습니다." });
  } catch (e) {
    console.error("inspection save:", e);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
  }
}
