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

// productionplanning.xml::workDiaryGridList 대응 - 작업일지 목록
export async function POST(request: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });

  const body = await request.json().catch(() => ({}));
  const projectNos: string[] = Array.isArray(body.project_nos)
    ? body.project_nos.filter(Boolean).map(String)
    : [];

  const conditions: string[] = ["1=1"];
  const params: unknown[] = [];
  let idx = 1;

  if (body.year) {
    conditions.push(`TO_CHAR(T.regdate, 'YYYY') = $${idx++}`);
    params.push(String(body.year));
  }
  if (body.search_division) {
    conditions.push(`T.division = $${idx++}`);
    params.push(String(body.search_division));
  }
  if (projectNos.length > 0) {
    const placeholders = projectNos.map(() => `$${idx++}`).join(",");
    conditions.push(`T.contract_objid IN (${placeholders})`);
    params.push(...projectNos);
  }
  if (body.unit_code) {
    conditions.push(`T.unit_code = $${idx++}`);
    params.push(String(body.unit_code));
  }
  if (body.busUsersDeptId) {
    conditions.push(`COALESCE(
      (SELECT dept_code FROM user_info WHERE user_id = T.worker_id),
      (SELECT dept_code FROM user_info_history WHERE user_id = T.worker_id ORDER BY regdate DESC LIMIT 1)
    ) = $${idx++}`);
    params.push(String(body.busUsersDeptId));
  }
  if (body.worker) {
    conditions.push(`T.worker_id = $${idx++}`);
    params.push(String(body.worker));
  }
  if (body.search_status) {
    conditions.push(`T.status = $${idx++}`);
    params.push(String(body.search_status));
  }

  const where = conditions.join(" AND ");

  const sql = `
    SELECT
      T.objid::text AS "OBJID",
      T.contract_objid AS "CONTRACT_OBJID",
      (SELECT project_no FROM project_mgmt AS O WHERE O.objid = T.contract_objid) AS "PROJECT_NO",
      T.unit_code AS "UNIT_CODE",
      (SELECT O.unit_no || '-' || O.task_name FROM pms_wbs_task AS O WHERE O.objid = T.unit_code) AS "UNIT_CODE_NAME",
      T.division AS "DIVISION",
      T.task_name AS "TASK_NAME",
      T.worker_id AS "WORKER_ID",
      COALESCE(
        (SELECT dept_name FROM user_info WHERE user_id = T.worker_id),
        (SELECT dept_name FROM user_info_history WHERE user_id = T.worker_id ORDER BY regdate DESC LIMIT 1),
        ''
      ) AS "DEPT_NAME",
      COALESCE(
        (SELECT user_name FROM user_info WHERE user_id = T.worker_id),
        (SELECT user_name FROM user_info_history WHERE user_id = T.worker_id ORDER BY regdate DESC LIMIT 1),
        T.worker_id
      ) AS "WORKER_NAME",
      T.work_start_date AS "WORK_START_DATE",
      T.work_end_date AS "WORK_END_DATE",
      T.work_hour AS "WORK_HOUR",
      T.remark AS "REMARK",
      T.regdate AS "REGDATE",
      T.writer AS "WRITER",
      T.sourcing_type AS "SOURCING_TYPE",
      T.production_type AS "PRODUCTION_TYPE",
      COALESCE(
        (SELECT user_name FROM user_info WHERE user_id = T.writer),
        (SELECT user_name FROM user_info_history WHERE user_id = T.writer ORDER BY regdate DESC LIMIT 1),
        T.writer
      ) AS "WRITER_NAME",
      TO_CHAR(T.regdate, 'YYYY-MM-DD') AS "REG_DATE_TEXT",
      T.status AS "STATUS",
      CASE WHEN T.status = 'write' THEN '작성중'
           WHEN T.status = 'complete' THEN '확인완료'
           ELSE '' END AS "STATUS_TITLE"
    FROM work_diary AS T
    WHERE ${where}
    ORDER BY T.regdate DESC
  `;

  const rows = await queryRows(sql, params);
  return NextResponse.json({ RESULTLIST: rows, TOTAL_CNT: rows.length });
}
