import { fetchWithAuth } from "./client";

export interface AdminStatsData {
  total_users: number;
  total_queries: number;
  total_citations: number;
  citation_rate: number;
  today_active_users: number;
}

export interface AdminUser {
  id: string;
  email: string;
  name: string | null;
  plan: string;
  is_active: boolean;
  is_admin: boolean;
  email_verified: boolean;
  query_count: number;
  created_at: string;
}

export interface AdminUserListResponse {
  items: AdminUser[];
  total: number;
}

export interface AdminActionResponse {
  message: string;
}

export const adminApi = {
  getStats: async (token: string) =>
    fetchWithAuth("/api/v1/admin/stats", {}, token) as Promise<AdminStatsData>,
  getUsers: async (
    token: string,
    params?: { skip?: number; limit?: number; search?: string }
  ) => {
    const query = params
      ? "?" +
        new URLSearchParams(
          Object.entries(params).filter(
            ([, v]) => v !== undefined
          ) as [string, string][]
        ).toString()
      : "";
    return fetchWithAuth(`/api/v1/admin/users${query}`, {}, token) as Promise<AdminUserListResponse>;
  },
  getUserDetail: async (token: string, userId: string) =>
    fetchWithAuth(`/api/v1/admin/users/${userId}`, {}, token) as Promise<AdminUser>,
  toggleUserActive: async (token: string, userId: string) =>
    fetchWithAuth(
      `/api/v1/admin/users/${userId}/toggle-active`,
      { method: "POST" },
      token
    ) as Promise<AdminActionResponse>,
  updateUserPlan: async (token: string, userId: string, plan: string) =>
    fetchWithAuth(
      `/api/v1/admin/users/${userId}/update-plan`,
      {
        method: "PUT",
        body: JSON.stringify({ plan }),
      },
      token
    ) as Promise<AdminActionResponse>,
};
