import { fetchJson } from "./client";
import type { AdminRedeemCodesResponse, AdminRedeemRedemptionsResponse, ApiResult, PaymentSummaryResponse, RedeemResponse, SubscriptionSummaryResponse } from "@/types";

export const billingAPI = {
  redeem: (body: { code: string; idempotencyKey?: string }): Promise<ApiResult<RedeemResponse>> => fetchJson("/v1/redeem", { method: "POST", body: JSON.stringify(body), timeoutMs: 12000, timeoutName: "redeem" }),
  subscriptionSummary: (): Promise<ApiResult<SubscriptionSummaryResponse>> => fetchJson("/v1/subscription/summary", { timeoutMs: 12000, timeoutName: "subscription summary" }),
  paymentSummary: (): Promise<ApiResult<PaymentSummaryResponse>> => fetchJson("/v1/payments/summary", { timeoutMs: 12000, timeoutName: "payment summary" }),
  adminRedeemCodes: (params: { limit?: number; status?: string } = {}): Promise<ApiResult<AdminRedeemCodesResponse>> => fetchJson(redeemPath("/v1/admin/billing/redeem-codes", params), { timeoutMs: 12000, timeoutName: "admin redeem codes" }),
  createAdminRedeemCode: (body: Record<string, unknown>): Promise<ApiResult<AdminRedeemCodesResponse>> => fetchJson("/v1/admin/billing/redeem-codes", { method: "POST", body: JSON.stringify(body), timeoutMs: 12000, timeoutName: "create redeem code" }),
  updateAdminRedeemCode: (codeId: string, body: Record<string, unknown>): Promise<ApiResult<AdminRedeemCodesResponse>> => fetchJson(`/v1/admin/billing/redeem-codes/${encodeURIComponent(codeId)}`, { method: "PATCH", body: JSON.stringify(body), timeoutMs: 12000, timeoutName: "update redeem code" }),
  adminRedeemRedemptions: (params: { limit?: number; userId?: string; codeId?: string } = {}): Promise<ApiResult<AdminRedeemRedemptionsResponse>> => fetchJson(redeemPath("/v1/admin/billing/redeem-redemptions", params), { timeoutMs: 12000, timeoutName: "admin redeem redemptions" })
};

function redeemPath(path: string, params: Record<string, unknown> = {}): 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;
}
