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

// productionplanning.xml::workDiaryConfirm 대응 - 작업일지 팀장확인
// STATUS = 'write' 인 항목만 'complete'로 변경 가능 (JSP 측 제약)
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 checkArr: string[] = Array.isArray(body.checkArr)
    ? body.checkArr.filter(Boolean).map(String)
    : typeof body.checkArr === "string" && body.checkArr
      ? body.checkArr.split(",").map((s: string) => s.trim()).filter(Boolean)
      : [];

  if (checkArr.length === 0) {
    return NextResponse.json({ success: false, msg: "선택된 데이터가 없습니다." }, { status: 400 });
  }

  try {
    const placeholders = checkArr.map((_, i) => `$${i + 1}`).join(",");
    const count = await execute(
      `UPDATE work_diary SET status = 'complete' WHERE objid IN (${placeholders}) AND status = 'write'`,
      checkArr,
    );
    return NextResponse.json({ success: true, msg: `${count}건 확정되었습니다.` });
  } catch (error) {
    console.error("작업일지 팀장확인:", error);
    return NextResponse.json(
      { success: false, msg: "확정 중 오류가 발생했습니다." },
      { status: 500 },
    );
  }
}
