import { apiRequest } from "@/lib/api/api-service";
import { ApiResponse, PaginatedData } from "@/types/api-response";
import type {
  AdminPaginationParams,
  AdminUserDto,
  AddLeagueTierDto,
  AnalyticsOverviewDto,
  LeagueTierDto,
  LeagueTierStatsDto,
  ModelPerformanceDto,
  RetrainStatusDto,
  SettingDto,
  UpdateLeagueTierDto,
  UpdateSettingDto,
  UpdateUserRoleDto,
  UpdateUserSubscriptionDto,
  UsageLimitDto,
} from "./types";

/**
 * Admin Service
 * Backend: /api/admin/*
 */

// Analytics
const getAnalyticsOverview = () => {
  return apiRequest<ApiResponse<AnalyticsOverviewDto>>({
    url: "/admin/analytics/overview",
    client: "admin",
    method: "get",
  });
};

// Model Performance (forward-test)
const getModelPerformance = (days?: number) => {
  return apiRequest<ApiResponse<ModelPerformanceDto>>({
    url: "/admin/model-performance",
    client: "admin",
    method: "get",
    params: days ? { days: String(days) } : undefined,
  });
};

// Settings
const getAllSettings = () => {
  return apiRequest<ApiResponse<Record<string, string>>>({
    url: "/admin/settings",
    client: "admin",
    method: "get",
  });
};

const updateSetting = (key: string, dto: UpdateSettingDto) => {
  return apiRequest<ApiResponse<SettingDto>>({
    url: `/admin/settings/${key}`,
    client: "admin",
    method: "put",
    data: dto,
  });
};

// Usage Limits
const getAllUsageLimits = (params?: AdminPaginationParams) => {
  return apiRequest<ApiResponse<PaginatedData<UsageLimitDto>>>({
    url: "/admin/usage-limits",
    client: "admin",
    method: "get",
    params,
  });
};

const resetAllUsageLimits = () => {
  return apiRequest<ApiResponse<{ count: number }>>({
    url: "/admin/usage-limits/reset-all",
    client: "admin",
    method: "post",
  });
};

const resetUserUsageLimits = (userId: string) => {
  return apiRequest<ApiResponse<null>>({
    url: `/admin/usage-limits/reset/${userId}`,
    client: "admin",
    method: "post",
  });
};

// Users
const getAllUsers = (params?: AdminPaginationParams) => {
  return apiRequest<ApiResponse<PaginatedData<AdminUserDto>>>({
    url: "/admin/users",
    client: "admin",
    method: "get",
    params,
  });
};

const getUserById = (id: string) => {
  return apiRequest<ApiResponse<AdminUserDto>>({
    url: `/admin/users/${id}`,
    client: "admin",
    method: "get",
  });
};

const deleteUser = (id: string) => {
  return apiRequest<ApiResponse<null>>({
    url: `/admin/users/${id}`,
    client: "admin",
    method: "delete",
  });
};

const updateUserRole = (id: string, dto: UpdateUserRoleDto) => {
  return apiRequest<ApiResponse<AdminUserDto>>({
    url: `/admin/users/${id}/role`,
    client: "admin",
    method: "put",
    data: dto,
  });
};

const updateUserSubscription = (id: string, dto: UpdateUserSubscriptionDto) => {
  return apiRequest<ApiResponse<AdminUserDto>>({
    url: `/admin/users/${id}/subscription`,
    client: "admin",
    method: "put",
    data: dto,
  });
};

const toggleUserActive = (id: string) => {
  return apiRequest<ApiResponse<AdminUserDto>>({
    url: `/admin/users/${id}/toggle-active`,
    client: "admin",
    method: "put",
  });
};

// League Tiers
const getLeagueTiers = (active?: boolean) => {
  return apiRequest<ApiResponse<LeagueTierDto[]>>({
    url: "/admin/league-tiers",
    client: "admin",
    method: "get",
    params: active !== undefined ? { active: String(active) } : undefined,
  });
};

const getLeagueTierStats = () => {
  return apiRequest<ApiResponse<LeagueTierStatsDto>>({
    url: "/admin/league-tiers/stats",
    client: "admin",
    method: "get",
  });
};

const addLeagueTier = (dto: AddLeagueTierDto) => {
  return apiRequest<ApiResponse<LeagueTierDto>>({
    url: "/admin/league-tiers",
    client: "admin",
    method: "post",
    data: dto,
  });
};

const updateLeagueTier = (leagueId: string, dto: UpdateLeagueTierDto) => {
  return apiRequest<ApiResponse<LeagueTierDto>>({
    url: `/admin/league-tiers/${leagueId}/tier`,
    client: "admin",
    method: "put",
    data: dto,
  });
};

const deactivateLeagueTier = (leagueId: string) => {
  return apiRequest<ApiResponse<LeagueTierDto>>({
    url: `/admin/league-tiers/${leagueId}/deactivate`,
    client: "admin",
    method: "put",
  });
};

const deleteLeagueTier = (leagueId: string) => {
  return apiRequest<ApiResponse<null>>({
    url: `/admin/league-tiers/${leagueId}`,
    client: "admin",
    method: "delete",
  });
};

const syncLeagueTiers = () => {
  return apiRequest<ApiResponse<{ count: number; path: string }>>({
    url: "/admin/league-tiers/sync",
    client: "admin",
    method: "post",
  });
};

const triggerRetrain = () => {
  return apiRequest<ApiResponse<{ status: string; message: string }>>({
    url: "/admin/league-tiers/retrain",
    client: "admin",
    method: "post",
  });
};

const getRetrainStatus = () => {
  return apiRequest<ApiResponse<RetrainStatusDto>>({
    url: "/admin/league-tiers/retrain/status",
    client: "admin",
    method: "get",
  });
};

export const adminService = {
  getAnalyticsOverview,
  getModelPerformance,
  getAllSettings,
  updateSetting,
  getAllUsageLimits,
  resetAllUsageLimits,
  resetUserUsageLimits,
  getAllUsers,
  getUserById,
  deleteUser,
  updateUserRole,
  updateUserSubscription,
  toggleUserActive,
  // League Tiers
  getLeagueTiers,
  getLeagueTierStats,
  addLeagueTier,
  updateLeagueTier,
  deactivateLeagueTier,
  deleteLeagueTier,
  syncLeagueTiers,
  triggerRetrain,
  getRetrainStatus,
};
