// 모모 사용자 인증 — user_info 테이블 사용 (momo_users 폐기 v0.2)
// 기존 FITO AES 암호화와 동일하게 user_password 사용 — verifyCredentials 와 호환
import { queryOne, execute } from "./db";
import { encrypt } from "./encrypt";

export interface MomoUser {
  objid: string;        // = user_id
  email: string;
  companyName: string;  // = user_name
  ceoName: string;
  bizNo: string;
  phone: string;
  address: string;
  role: "USER" | "ADMIN";
  status: string;
  userId: string;
  userName: string;
  isAdmin: boolean;
}

export interface SignupInput {
  email: string;
  password: string;
  companyName: string;
  ceoName?: string;
  bizNo?: string;
  phone?: string;
  address?: string;
}

function rowToUser(r: Record<string, unknown>): MomoUser {
  const userType = String(r.USER_TYPE || "").toUpperCase();
  const role: "USER" | "ADMIN" = userType === "A" ? "ADMIN" : "USER";
  const userId = (r.USER_ID as string) || "";
  const email = (r.EMAIL as string) || userId;
  const companyName = (r.USER_NAME as string) || "";
  return {
    objid: userId,
    email,
    companyName,
    ceoName: (r.CEO_NAME as string) || (r.USER_NAME_ENG as string) || "",
    bizNo: (r.BIZ_NO as string) || "",
    phone: (r.CELL_PHONE as string) || (r.TEL as string) || "",
    address: (r.ADDRESS as string) || "",
    role,
    status: (r.STATUS as string) || "active",
    userId,
    userName: companyName,
    isAdmin: role === "ADMIN",
  };
}

export async function findMomoUserByEmail(email: string): Promise<MomoUser | null> {
  const row = await queryOne<Record<string, unknown>>(
    `SELECT user_id AS "USER_ID", user_name AS "USER_NAME",
            user_name_eng AS "USER_NAME_ENG",
            email AS "EMAIL", cell_phone AS "CELL_PHONE", tel AS "TEL",
            user_type AS "USER_TYPE", status AS "STATUS",
            biz_no AS "BIZ_NO", ceo_name AS "CEO_NAME",
            address AS "ADDRESS"
     FROM user_info
     WHERE LOWER(user_id) = LOWER($1) OR LOWER(email) = LOWER($1)
     LIMIT 1`,
    [email]
  );
  if (!row) return null;
  return rowToUser(row);
}

export async function verifyMomoCredentials(
  email: string,
  password: string
): Promise<{ success: boolean; user?: MomoUser; error?: string }> {
  const row = await queryOne<{ user_password: string; status: string }>(
    `SELECT user_password, status FROM user_info
     WHERE LOWER(user_id) = LOWER($1) OR LOWER(email) = LOWER($1) LIMIT 1`,
    [email]
  );
  if (!row) return { success: false, error: "사용자가 존재하지 않습니다." };
  if (row.status && row.status !== "active") {
    return { success: false, error: "계정이 비활성화 상태입니다." };
  }
  const stored = row.user_password ?? "";
  if (!stored) {
    return { success: false, error: "비밀번호 미설정 — 관리자에게 비밀번호 초기화 요청하세요." };
  }
  const enc = encrypt(password);
  if (stored !== enc) {
    return { success: false, error: "비밀번호가 일치하지 않습니다." };
  }
  const user = await findMomoUserByEmail(email);
  return user ? { success: true, user } : { success: false, error: "사용자 조회 실패" };
}

export async function signupMomoUser(input: SignupInput): Promise<{ success: boolean; user?: MomoUser; error?: string }> {
  const email = input.email.trim().toLowerCase();
  if (!email || !input.password || !input.companyName) {
    return { success: false, error: "이메일/비밀번호/업체명은 필수입니다." };
  }
  if (input.password.length < 4) {
    return { success: false, error: "비밀번호는 4자 이상이어야 합니다." };
  }

  const dup = await queryOne(
    `SELECT 1 FROM user_info WHERE LOWER(user_id) = LOWER($1) OR LOWER(email) = LOWER($1)`,
    [email]
  );
  if (dup) return { success: false, error: "이미 가입된 이메일입니다." };

  const enc = encrypt(input.password);
  await execute(
    `INSERT INTO user_info
       (user_id, user_password, user_name, email, cell_phone,
        user_type, user_type_name, biz_no, ceo_name, address, status, regdate)
     VALUES ($1, $2, $3, $1, $4, 'U', '사용자', $5, $6, $7, 'active', NOW())`,
    [
      email,
      enc,
      input.companyName.trim(),
      input.phone?.trim() ?? "",
      input.bizNo?.trim() ?? "",
      input.ceoName?.trim() ?? "",
      input.address?.trim() ?? "",
    ]
  );

  const user = await findMomoUserByEmail(email);
  return user ? { success: true, user } : { success: false, error: "가입 후 조회 실패" };
}
