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

// productionplanning.xml::mergeWorkDiaryInfo 대응 - 작업일지 등록/수정
// INSERT ... ON CONFLICT (objid) DO UPDATE. STATUS는 신규 시 'write' 고정.
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 isNew = body.actionType === "regist" || !body.objId;
  const objId = isNew ? createObjectId() : String(body.objId);
  const contractObjid = String(body.project_objid || body.contract_objid || "");

  try {
    await execute(
      `INSERT INTO work_diary (
         objid, contract_objid, unit_code, division, task_name,
         worker_id, work_start_date, work_end_date, work_hour, remark,
         status, writer, regdate, sourcing_type, production_type
       ) VALUES (
         $1, $2, $3, $4, $5,
         $6, $7, $8, $9, $10,
         'write', $11, now(), $12, $13
       )
       ON CONFLICT (objid) DO UPDATE SET
         contract_objid  = EXCLUDED.contract_objid,
         unit_code       = EXCLUDED.unit_code,
         division        = EXCLUDED.division,
         task_name       = EXCLUDED.task_name,
         worker_id       = EXCLUDED.worker_id,
         work_start_date = EXCLUDED.work_start_date,
         work_end_date   = EXCLUDED.work_end_date,
         work_hour       = EXCLUDED.work_hour,
         remark          = EXCLUDED.remark,
         sourcing_type   = EXCLUDED.sourcing_type,
         production_type = EXCLUDED.production_type`,
      [
        objId,
        contractObjid,
        String(body.unit_code || ""),
        String(body.division || ""),
        String(body.task_name || ""),
        String(body.worker_id || user.userId),
        String(body.work_start_date || ""),
        String(body.work_end_date || ""),
        String(body.work_hour || ""),
        String(body.remark || ""),
        user.userId,
        String(body.sourcing_type || ""),
        String(body.production_type || ""),
      ],
    );
    return NextResponse.json({
      success: true,
      objId,
      message: isNew ? "등록되었습니다." : "수정되었습니다.",
    });
  } catch (error) {
    console.error("작업일지 저장:", error);
    return NextResponse.json(
      { success: false, message: "저장 중 오류가 발생했습니다." },
      { status: 500 },
    );
  }
}
