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

// 부서 등록/수정
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 {
    actionType,
    dept_code,
    dept_name,
    parent_dept_code,
    master_sabun,
    master_user_id,
    location,
    location_name,
    status,
    sales_yn,
    company_name,
  } = body as Record<string, string | undefined>;

  if (!dept_name) {
    return NextResponse.json({ success: false, message: "부서명은 필수입니다." }, { status: 400 });
  }

  if (actionType === "regist") {
    // 부서코드 자동 생성: DEPT### 최대값 + 1
    let code = (dept_code || "").trim();
    if (!code) {
      const row = await queryOne<{ MAX_CODE: string | null }>(
        `SELECT MAX(dept_code) AS "MAX_CODE" FROM dept_info WHERE dept_code ~ '^DEPT[0-9]+$'`
      );
      const max = row?.MAX_CODE;
      const next = max ? parseInt(max.replace(/^DEPT/, ""), 10) + 1 : 1;
      code = `DEPT${String(next).padStart(3, "0")}`;
    }

    const dup = await queryOne<{ cnt: string }>(
      `SELECT COUNT(*)::text AS cnt FROM dept_info WHERE dept_code = $1`,
      [code]
    );
    if (dup && Number(dup.cnt) > 0) {
      return NextResponse.json({ success: false, message: "이미 존재하는 부서코드입니다." }, { status: 400 });
    }

    await execute(
      `INSERT INTO dept_info
         (dept_code, dept_name, parent_dept_code, master_sabun, master_user_id,
          location, location_name, regdate, status, sales_yn, company_name)
       VALUES ($1, $2, $3, $4, $5, $6, $7, NOW(), COALESCE($8,'active'), $9, $10)`,
      [
        code,
        dept_name,
        parent_dept_code || null,
        master_sabun || null,
        master_user_id || null,
        location || null,
        location_name || null,
        status || "active",
        sales_yn || "N",
        company_name || "모모유통",
      ]
    );
    return NextResponse.json({ success: true, message: "등록되었습니다.", dept_code: code });
  }

  // 수정
  await execute(
    `UPDATE dept_info SET
       dept_name = $1,
       parent_dept_code = $2,
       master_sabun = $3,
       master_user_id = $4,
       location = $5,
       location_name = $6,
       status = COALESCE($7, status),
       sales_yn = $8,
       company_name = $9
     WHERE dept_code = $10`,
    [
      dept_name,
      parent_dept_code || null,
      master_sabun || null,
      master_user_id || null,
      location || null,
      location_name || null,
      status || null,
      sales_yn || "N",
      company_name || null,
      dept_code,
    ]
  );
  return NextResponse.json({ success: true, message: "수정되었습니다.", dept_code });
}
