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

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 isNew = body.actionType === "regist";
  const client = await pool.connect();
  try {
    if (isNew) {
      const encPassword = encrypt(body.password || "1234");
      await client.query(
        `INSERT INTO user_info (user_id, user_name, sabun, dept_code, dept_name, position_name,
          email, cell_phone, user_type, user_password, tel, regdate)
         VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, now())
         ON CONFLICT (user_id) DO UPDATE SET
          user_name=EXCLUDED.user_name, sabun=EXCLUDED.sabun,
          dept_code=EXCLUDED.dept_code, dept_name=EXCLUDED.dept_name,
          position_name=EXCLUDED.position_name, email=EXCLUDED.email,
          cell_phone=EXCLUDED.cell_phone, user_type=EXCLUDED.user_type,
          tel=EXCLUDED.tel`,
        [body.user_id || "", body.user_name || "", body.sabun || "",
         body.dept_code || "", body.dept_name || "", body.position_name || "",
         body.email || "", body.cell_phone || "", body.user_type || "",
         encPassword, body.tel || ""]
      );
    } else {
      // Update without changing password
      const unlimited = body.unlimited_qty === "Y" ? "Y" : "N";
      const viewHidden = body.view_hidden === "Y" ? "Y" : "N";
      // 빈 문자열 / undefined → NULL 처리
      const defaultWh = body.default_wh_objid && String(body.default_wh_objid).trim() !== "" ? body.default_wh_objid : null;
      const stmtBranch = body.statement_branch === "KIMPO" ? "KIMPO" : "HQ";
      await client.query(
        `UPDATE user_info SET
          user_name=$1, sabun=$2, dept_code=$3, dept_name=$4,
          position_name=$5, email=$6, cell_phone=$7, user_type=$8, tel=$9,
          address=COALESCE($11, address), ceo_name=COALESCE($12, ceo_name),
          biz_no=COALESCE($13, biz_no),
          unlimited_qty=$14, view_hidden=$15,
          default_wh_objid=$16,
          statement_branch=$17
         WHERE user_id=$10`,
        [body.user_name || "", body.sabun || "", body.dept_code || "",
         body.dept_name || "", body.position_name || "", body.email || "",
         body.cell_phone || "", body.user_type || "", body.tel || "",
         body.user_id || "",
         body.address ?? null, body.ceo_name ?? null, body.biz_no ?? null,
         unlimited, viewHidden, defaultWh, stmtBranch]
      );
    }
    return NextResponse.json({ success: true, message: isNew ? "등록되었습니다." : "수정되었습니다." });
  } catch (e) {
    console.error("User save:", e);
    return NextResponse.json({ success: false, message: "저장 중 오류가 발생했습니다." });
  } finally { client.release(); }
}
