import { apiRequest } from "@/lib/api/api-service";
import { ApiResponse, PaginatedData } from "@/types/api-response";
import type {
  AdminPaginationParams,
  AdminUserDto,
  AnalyticsOverviewDto,
  SettingDto,
  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",
  });
};

// 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",
  });
};

// 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",
  });
};

export const adminService = {
  getAnalyticsOverview,
  getAllSettings,
  updateSetting,
  getAllUsageLimits,
  resetAllUsageLimits,
  getAllUsers,
  getUserById,
  deleteUser,
  updateUserRole,
  updateUserSubscription,
  toggleUserActive,
};
