// 회원정보 수정 — 본인 전용 (이름/연락처/주소/이메일/비밀번호 변경)
import { NextRequest, NextResponse } from "next/server";
import { getSession, createSession } from "@/lib/session";
import { queryOne, execute } from "@/lib/db";
import { encrypt } from "@/lib/encrypt";

export async function GET() {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });
  const userId = user.objid || user.userId;
  const row = await queryOne<Record<string, string>>(
    `SELECT user_id     AS "USER_ID",
            user_name   AS "USER_NAME",
            email       AS "EMAIL",
            cell_phone  AS "CELL_PHONE",
            tel         AS "TEL",
            address     AS "ADDRESS",
            ceo_name    AS "CEO_NAME",
            biz_no      AS "BIZ_NO",
            user_type   AS "USER_TYPE"
     FROM user_info WHERE user_id = $1`,
    [userId]
  );
  if (!row) return NextResponse.json({ success: false, message: "사용자를 찾을 수 없습니다." }, { status: 404 });
  return NextResponse.json({ success: true, data: row });
}

export async function POST(req: NextRequest) {
  const user = await getSession();
  if (!user) return NextResponse.json({ success: false }, { status: 401 });
  const userId = user.objid || user.userId;

  const body = await req.json().catch(() => ({}));
  const {
    userName,
    email,
    cellPhone,
    tel,
    address,
    ceoName,
    bizNo,
    currentPassword,
    newPassword,
  } = body as Record<string, string>;

  // 비밀번호 변경 요청이면 현재 비밀번호 검증
  if (newPassword) {
    if (!currentPassword) {
      return NextResponse.json({ success: false, message: "현재 비밀번호를 입력하세요." }, { status: 400 });
    }
    if (newPassword.length < 4) {
      return NextResponse.json({ success: false, message: "새 비밀번호는 4자 이상이어야 합니다." }, { status: 400 });
    }
    const row = await queryOne<{ user_password: string }>(
      `SELECT user_password FROM user_info WHERE user_id = $1`,
      [userId]
    );
    if (!row || row.user_password !== encrypt(currentPassword)) {
      return NextResponse.json({ success: false, message: "현재 비밀번호가 일치하지 않습니다." }, { status: 400 });
    }
    await execute(
      `UPDATE user_info SET user_password = $2 WHERE user_id = $1`,
      [userId, encrypt(newPassword)]
    );
  }

  // 일반 정보 업데이트 (NULL이면 기존값 유지)
  await execute(
    `UPDATE user_info SET
       user_name  = COALESCE($2, user_name),
       email      = COALESCE($3, email),
       cell_phone = COALESCE($4, cell_phone),
       tel        = COALESCE($5, tel),
       address    = COALESCE($6, address),
       ceo_name   = COALESCE($7, ceo_name),
       biz_no     = COALESCE($8, biz_no)
     WHERE user_id = $1`,
    [userId,
     userName ?? null, email ?? null, cellPhone ?? null,
     tel ?? null, address ?? null, ceoName ?? null, bizNo ?? null]
  );

  // 세션의 표시 정보 갱신 (userName, email, cellPhone)
  if (userName || email || cellPhone) {
    await createSession({
      ...user,
      userName: userName ?? user.userName,
      email: email ?? user.email,
      cellPhone: cellPhone ?? user.cellPhone,
      companyName: userName ?? user.companyName,
    });
  }

  return NextResponse.json({ success: true });
}
