import { fetchJson } from "./client";
import type { AccessUserStatus, AdminAuditResponse, AdminBillingMutationResponse, AdminBillingPlansResponse, AdminBillingSummary, AdminBillingUserDetailResponse, AdminBillingUsersResponse, AdminUsageRow, ApiResult, UsageLedgerRow, UsageSummary } from "@/types";

export const usageAPI = {
  summary: (): Promise<ApiResult<UsageSummary>> => fetchJson("/v1/usage/summary", { timeoutMs: 12000, timeoutName: "usage summary" }),
  adminBillingSummary: (): Promise<ApiResult<AdminBillingSummary>> => fetchJson("/v1/admin/billing/summary", { timeoutMs: 12000, timeoutName: "admin billing summary" }),
  adminPlans: (): Promise<ApiResult<AdminBillingPlansResponse>> => fetchJson("/v1/admin/billing/plans", { timeoutMs: 12000, timeoutName: "admin billing plans" }),
  adminUsage: (params: AdminAuditParams = {}): Promise<ApiResult<AdminAuditResponse<AdminUsageRow>>> => fetchJson(auditPath("/v1/admin/billing/usage", params), { timeoutMs: 12000, timeoutName: "admin usage" }),
  adminLedger: (params: AdminAuditParams = {}): Promise<ApiResult<AdminAuditResponse<UsageLedgerRow>>> => fetchJson(auditPath("/v1/admin/billing/ledger", params), { timeoutMs: 12000, timeoutName: "admin ledger" }),
  adminUsageExportUrl: (params: AdminAuditParams = {}): string => auditPath("/v1/admin/billing/usage/export", { ...params, limit: params.limit ?? 1000 }),
  adminLedgerExportUrl: (params: AdminAuditParams = {}): string => auditPath("/v1/admin/billing/ledger/export", { ...params, limit: params.limit ?? 1000 }),
  adminUsers: (params: { page?: number; pageSize?: number; search?: string; status?: string; role?: string } = {}): Promise<ApiResult<AdminBillingUsersResponse>> => {
    const query = new URLSearchParams({ page: String(params.page ?? 1), pageSize: String(params.pageSize ?? 25) });
    if (params.search) query.set("search", params.search);
    if (params.status) query.set("status", params.status);
    if (params.role) query.set("role", params.role);
    return fetchJson(`/v1/admin/billing/users?${query.toString()}`, { timeoutMs: 12000, timeoutName: "admin users" });
  },
  adminUser: (userId: string): Promise<ApiResult<AdminBillingUserDetailResponse>> => fetchJson(`/v1/admin/billing/users/${encodeURIComponent(userId)}`, { timeoutMs: 12000, timeoutName: "admin user detail" }),
  createAdminUser: (body: Record<string, unknown>): Promise<ApiResult<AdminBillingMutationResponse>> => fetchJson("/v1/admin/billing/users", { method: "POST", body: JSON.stringify(body), timeoutMs: 12000, timeoutName: "create admin user" }),
  updateAdminUser: (userId: string, body: Record<string, unknown>): Promise<ApiResult<AdminBillingMutationResponse>> => fetchJson(`/v1/admin/billing/users/${encodeURIComponent(userId)}`, { method: "PATCH", body: JSON.stringify(body), timeoutMs: 12000, timeoutName: "update admin user" }),
  adjustAdminCredits: (userId: string, body: Record<string, unknown>): Promise<ApiResult<AdminBillingMutationResponse>> => fetchJson(`/v1/admin/billing/users/${encodeURIComponent(userId)}/credits/adjust`, { method: "POST", body: JSON.stringify(body), timeoutMs: 12000, timeoutName: "adjust admin credits" }),
  updateAdminUserStatus: (userId: string, status: AccessUserStatus): Promise<ApiResult<AdminBillingMutationResponse>> => fetchJson(`/v1/admin/billing/users/${encodeURIComponent(userId)}/status`, { method: "PATCH", body: JSON.stringify({ status }), timeoutMs: 12000, timeoutName: "admin user status" }),
  performance: (): Promise<ApiResult<UsageSummary>> => fetchJson("/v1/web-performance/summary", { timeoutMs: 12000, timeoutName: "web performance summary" })
};

export interface AdminAuditParams { page?: number; pageSize?: number; limit?: number; userId?: string; search?: string; serviceId?: string; resourceType?: string; apiKeyId?: string; status?: string; kind?: string; source?: string; idempotencyKey?: string; from?: string; to?: string }

function auditPath(path: string, params: AdminAuditParams = {}): string {
  const query = new URLSearchParams();
  for (const [key, value] of Object.entries(params)) {
    const text = String(value ?? "").trim();
    if (text) query.set(key, text);
  }
  const suffix = query.toString();
  return suffix ? `${path}?${suffix}` : path;
}
