import api from "@/lib/api/axios";
import type {
  ProviderDetail,
  ProviderListParams,
  ProviderListResponse,
  UpdateProviderStatusRequest,
  VerifyDocumentRequest,
  VerifyDocumentResponse,
} from "@/types/provider";

/**
 * Admin Provider Management API (`/providers/admin`).
 *
 * Guarded backend-side by `@Roles(ADMIN_SUPER, ADMIN_SUPPORT)`; the shared axios
 * client attaches the bearer token and `x-language` header.
 *
 * The backend validates with `forbidNonWhitelisted: true`, so undefined params
 * are stripped before sending — an explicit `undefined` would serialize away
 * anyway, but an empty `search=""` would not, and the backend would treat it as
 * a real (always-matching) filter.
 */
export async function listProvidersApi(
  params: ProviderListParams,
): Promise<ProviderListResponse> {
  const { data } = await api.get<ProviderListResponse>("/providers/admin", {
    params: {
      ...(params.search?.trim() ? { search: params.search.trim() } : {}),
      ...(params.status ? { status: params.status } : {}),
      ...(params.page ? { page: params.page } : {}),
      ...(params.limit ? { limit: params.limit } : {}),
    },
  });
  return data;
}

export async function getProviderDetailApi(
  id: string,
): Promise<ProviderDetail> {
  const { data } = await api.get<ProviderDetail>(`/providers/admin/${id}`);
  return data;
}

/**
 * Update account status and/or the platform commission rate.
 *
 * Setting `ACTIVE` on a provider that isn't already active stamps `verifiedAt`
 * backend-side. Nothing clears it on suspend/reject.
 */
export async function updateProviderStatusApi(
  id: string,
  payload: UpdateProviderStatusRequest,
): Promise<void> {
  await api.put(`/providers/admin/${id}/status`, payload);
}

/** Approve or reject a single KYC document */
export async function verifyProviderDocumentApi(
  providerId: string,
  documentId: string,
  payload: VerifyDocumentRequest,
): Promise<VerifyDocumentResponse> {
  const { data } = await api.put<VerifyDocumentResponse>(
    `/providers/admin/${providerId}/documents/${documentId}`,
    payload,
  );
  return data;
}
