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

// 이슈 저장/삭제/배포 (mergeissueInfo + planningDelete + planningRelease 대응)
// actionType: "regist" | "update" | "delete" | "release"
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 action = String(body.actionType || "");

  // 일괄 삭제 / 배포
  if (action === "delete" || action === "release") {
    const objIds: string[] = Array.isArray(body.objIds) ? body.objIds.map(String).filter(Boolean) : [];
    if (objIds.length === 0) {
      return NextResponse.json({ success: false, message: "선택된 대상이 없습니다." }, { status: 400 });
    }
    try {
      const placeholders = objIds.map((_, i) => `$${i + 1}`).join(",");
      if (action === "delete") {
        await execute(
          `DELETE FROM planning_issue WHERE objid IN (${placeholders}) AND status = 'write'`,
          objIds,
        );
        return NextResponse.json({ success: true, message: "삭제되었습니다." });
      }
      await execute(
        `UPDATE planning_issue SET status = 'release' WHERE objid IN (${placeholders}) AND status = 'write'`,
        objIds,
      );
      return NextResponse.json({ success: true, message: "배포되었습니다." });
    } catch (e) {
      console.error("issue bulk action:", e);
      return NextResponse.json({ success: false, message: "처리 중 오류가 발생했습니다." }, { status: 500 });
    }
  }

  // 단건 저장 (등록/수정)
  const isNew = !body.objId || action === "regist";
  const objId = isNew ? createObjectId() : String(body.objId);

  try {
    // 신규 시 이슈번호 자동 생성
    let issueNo = body.issue_no || "";
    if (isNew && !issueNo) {
      const year = new Date().getFullYear().toString().slice(2);
      const r = await queryOne<{ seq: number }>(
        `SELECT COALESCE(MAX(SUBSTR(issue_no, 7)::numeric), 0)::int + 1 AS seq
           FROM planning_issue WHERE issue_no LIKE $1`,
        [`ISU${year}-%`],
      );
      issueNo = `ISU${year}-${String(r?.seq || 1).padStart(4, "0")}`;
    }

    await execute(
      `INSERT INTO planning_issue (
         objid, issue_no, project_objid, unit_code, part_objid,
         issue_category, issue_type, content,
         design_userid, design_result, design_date,
         purchase_userid, purchase_result, purchase_date,
         quality_userid, quality_result, quality_date,
         production_userid, production_result, production_date,
         status, writer, reg_date
       ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $20, $21, $22, NOW())
       ON CONFLICT (objid) DO UPDATE SET
         project_objid = EXCLUDED.project_objid,
         unit_code = EXCLUDED.unit_code,
         part_objid = EXCLUDED.part_objid,
         issue_category = EXCLUDED.issue_category,
         issue_type = EXCLUDED.issue_type,
         content = EXCLUDED.content,
         design_userid = EXCLUDED.design_userid,
         design_result = EXCLUDED.design_result,
         design_date = EXCLUDED.design_date,
         purchase_userid = EXCLUDED.purchase_userid,
         purchase_result = EXCLUDED.purchase_result,
         purchase_date = EXCLUDED.purchase_date,
         quality_userid = EXCLUDED.quality_userid,
         quality_result = EXCLUDED.quality_result,
         quality_date = EXCLUDED.quality_date,
         production_userid = EXCLUDED.production_userid,
         production_result = EXCLUDED.production_result,
         production_date = EXCLUDED.production_date,
         status = EXCLUDED.status`,
      [
        objId, issueNo,
        body.project_objid || "",
        body.unit_code || "",
        body.part_objid || "",
        body.issue_category || "",
        body.issue_type || "",
        body.content || "",
        body.design_userid || "", body.design_result || "", body.design_date || "",
        body.purchase_userid || "", body.purchase_result || "", body.purchase_date || "",
        body.quality_userid || "", body.quality_result || "", body.quality_date || "",
        body.production_userid || "", body.production_result || "", body.production_date || "",
        body.status || "write",
        user.userId,
      ],
    );
    return NextResponse.json({ success: true, objId, issueNo, message: isNew ? "등록되었습니다." : "수정되었습니다." });
  } catch (e) {
    console.error("Issue save:", e);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." }, { status: 500 });
  }
}
