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

// productionplanning.xml::selectWorkDiaryInfo 대응 - 작업일지 상세
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 objId = String(body.objId || "");
  if (!objId) {
    return NextResponse.json({ success: false, message: "objId가 필요합니다." }, { status: 400 });
  }

  const row = await queryOne(
    `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 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",
       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",
       T.sourcing_type AS "SOURCING_TYPE",
       T.production_type AS "PRODUCTION_TYPE"
     FROM work_diary AS T
     WHERE T.objid = $1`,
    [objId],
  );

  return NextResponse.json({ success: true, data: row || null });
}
