// lib/api/clientLoginLogApi.ts
// Admin viewer calls for the client login log. Uses the SAME staff token +
// API_BASE convention as billingAdminApi.ts so it drops in with zero changes.

const API_BASE = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3007/api";

function staffToken(): string {
  if (typeof window === "undefined") return "";
  return (
    localStorage.getItem("token") ||
    localStorage.getItem("accessToken") ||
    localStorage.getItem("access_token") ||
    ""
  );
}

async function call<T = any>(
  path: string,
  method: "GET" | "POST" = "GET",
  body?: any,
): Promise<T> {
  const token = staffToken();
  const res = await fetch(`${API_BASE}${path}`, {
    method,
    headers: {
      "Content-Type": "application/json",
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
    },
    ...(body ? { body: JSON.stringify(body) } : {}),
  });
  const json = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(json?.message || `Error ${res.status}`);
  return json as T;
}

export interface ClientLoginLog {
  id: number;
  company_id: number | null;
  client_user_id: number | null;
  client_email: string | null;
  client_phone: string | null;
  login_method: string;
  status: "success" | "failed";
  failure_reason: string | null;
  ip_address: string | null;
  user_agent: string | null;
  device_type: string | null;
  browser: string | null;
  browser_version: string | null;
  os: string | null;
  os_version: string | null;
  token_id: number | null;
  session_id: string | null;
  created_at: string;
}

export interface LoginLogPage {
  rows: ClientLoginLog[];
  total: number;
  page: number;
  limit: number;
  pages: number;
}

export const clientLoginLogApi = {
  /**
   * Admin: paginated login history for one company.
   * GET /companies/:companyId/client-logins?page=&limit=&status=
   */
  listForCompany: (
    companyId: number,
    opts: { page?: number; limit?: number; status?: "success" | "failed" } = {},
  ) => {
    const q = new URLSearchParams();
    if (opts.page) q.set("page", String(opts.page));
    if (opts.limit) q.set("limit", String(opts.limit));
    if (opts.status) q.set("status", opts.status);
    const qs = q.toString() ? `?${q.toString()}` : "";
    return call<{ success: boolean; data: LoginLogPage }>(
      `/companies/${companyId}/client-logins${qs}`,
      "GET",
    );
  },
};
