import { queryOne } from "./db";
import { encrypt } from "./encrypt";
import { SUPER_ADMIN } from "./constants";
import { checkNull } from "./utils";
import type { User } from "@/types";

export async function verifyCredentials(
  userId: string,
  password: string
): Promise<{ success: boolean; user?: User; error?: string }> {
  const pwdRow = await queryOne<{ user_password: string }>(
    `SELECT user_password FROM user_info WHERE UPPER(user_id) = UPPER($1)`,
    [userId]
  );

  if (!pwdRow) {
    return { success: false, error: "사용자가 존재하지 않습니다." };
  }

  const encPwd = encrypt(password);
  const dbPwd = checkNull(pwdRow.user_password);

  if (dbPwd !== encPwd) {
    return { success: false, error: "패스워드가 일치하지 않습니다." };
  }

  // 사용자 상세 정보 - 따옴표 alias로 대문자 키 보장
  const userRow = await queryOne<Record<string, string>>(
    `SELECT UI.sabun AS "SABUN", UI.user_id AS "USER_ID", UI.user_name AS "USER_NAME",
            UI.user_name_eng AS "USER_NAME_ENG", UI.user_name_cn AS "USER_NAME_CN",
            UI.dept_code AS "DEPT_CODE", UI.dept_name AS "DEPT_NAME",
            UI.email AS "EMAIL", UI.position_code AS "POSITION_CODE",
            UI.position_name AS "POSITION_NAME", UI.tel AS "TEL",
            UI.cell_phone AS "CELL_PHONE", UI.user_type AS "USER_TYPE",
            UI.user_type_name AS "USER_TYPE_NAME",
            COALESCE(UI.partner_objid, '') AS "PARTNER_CD",
            AI.auth_name AS "AUTH_NAME"
     FROM user_info UI
     LEFT OUTER JOIN (
       SELECT ARRAY_TO_STRING(ARRAY_AGG(AM.auth_name), ',') AS auth_name,
              ASU.user_id
       FROM authority_master AM, authority_sub_user ASU
       WHERE AM.objid = ASU.master_objid
       GROUP BY ASU.user_id
     ) AI ON UI.user_id = AI.user_id
     WHERE UPPER(UI.user_id) = UPPER($1)`,
    [userId]
  );

  if (!userRow) {
    return { success: false, error: "사용자 정보를 조회할 수 없습니다." };
  }

  const user: User = {
    sabun: checkNull(userRow.SABUN),
    userId: checkNull(userRow.USER_ID),
    userName: checkNull(userRow.USER_NAME),
    userNameEng: checkNull(userRow.USER_NAME_ENG),
    userNameCn: checkNull(userRow.USER_NAME_CN),
    deptCode: checkNull(userRow.DEPT_CODE),
    deptName: checkNull(userRow.DEPT_NAME),
    positionCode: checkNull(userRow.POSITION_CODE),
    positionName: checkNull(userRow.POSITION_NAME),
    email: checkNull(userRow.EMAIL),
    tel: checkNull(userRow.TEL),
    cellPhone: checkNull(userRow.CELL_PHONE),
    userType: checkNull(userRow.USER_TYPE),
    userTypeName: checkNull(userRow.USER_TYPE_NAME),
    authName: checkNull(userRow.AUTH_NAME),
    partnerCd: checkNull(userRow.PARTNER_CD),
    isAdmin: checkNull(userRow.USER_ID).toLowerCase() === SUPER_ADMIN,
  };

  try {
    await queryOne(
      `INSERT INTO login_access_log(log_time, system_name, user_id, login_result, error_message, remote_addr, recptn_dt)
       VALUES (now(), 'PMS', UPPER($1), 'SUCCESS', '', '', TO_CHAR(now(), 'YYYYMMDDHH24MISS'))`,
      [userId]
    );
  } catch {
    // 로그 실패 무시
  }

  return { success: true, user };
}
