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

// 검사 리스트 조회 (project_mgmt.objid 기준)
// body: { contractObjid }
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 contractObjid = String(body.contractObjid || "");
  if (!contractObjid) return NextResponse.json({ RESULTLIST: [], HEADER: {} });

  const header = await queryOne(
    `SELECT objid::text AS "OBJID",
            project_no AS "PROJECT_NO",
            project_name AS "PROJECT_NAME",
            (SELECT supply_name FROM supply_mng WHERE objid::text = customer_objid LIMIT 1) AS "CUSTOMER_NAME"
       FROM project_mgmt WHERE objid = $1`,
    [contractObjid],
  );

  const rows = await queryRows(
    `SELECT I.objid::text AS "OBJID",
            I.parent_objid AS "PARENT_OBJID",
            I.unit_code AS "UNIT_CODE",
            I.internal_inspection_date AS "INTERNAL_INSPECTION_DATE",
            I.internal_inspection_result AS "INTERNAL_INSPECTION_RESULT",
            I.internal_inspection_id AS "INTERNAL_INSPECTION_ID",
            COALESCE((SELECT COUNT(1) FROM attach_file_info
                       WHERE target_objid = I.objid
                         AND doc_type = 'INSPECTION_CHECKLIST_FILE'
                         AND UPPER(COALESCE(status,'')) = 'ACTIVE'), 0) AS "CL01_CNT"
       FROM inspection_mgmt I
      WHERE I.parent_objid = $1
      ORDER BY I.regdate`,
    [contractObjid],
  );

  return NextResponse.json({ RESULTLIST: rows, HEADER: header || {} });
}
