import { query } from "./db";

export async function ensureAdminLoginLogsTable() {
  await query(`
    CREATE TABLE IF NOT EXISTS admin_login_logs (
      id BIGINT AUTO_INCREMENT PRIMARY KEY,
      outcome VARCHAR(20) NOT NULL,
      ip VARCHAR(64) NULL,
      user_agent VARCHAR(255) NULL,
      meta JSON NULL,
      created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
      INDEX idx_created (created_at),
      INDEX idx_outcome (outcome)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
  `);
}

export async function logAdminLogin(input: {
  outcome: "success" | "failure";
  ip?: string | null;
  userAgent?: string | null;
  meta?: Record<string, unknown>;
}) {
  try {
    await ensureAdminLoginLogsTable();
    await query(
      `INSERT INTO admin_login_logs (outcome, ip, user_agent, meta)
       VALUES (:outcome, :ip, :user_agent, :meta)`,
      {
        outcome: input.outcome,
        ip: input.ip || null,
        user_agent: input.userAgent?.slice(0, 250) || null,
        meta: JSON.stringify(input.meta || {}),
      },
    );
  } catch (e) {
    console.error("admin login log failed", e);
  }
}
