/**
 * Quota Management API
 */

import apiClient from './client';
import { QuotaOverage } from './auth';

export interface QuotaUsage {
  current: number;
  limit: number;
  display_name: string;
}

export interface QuotaStatus {
  active_overages: QuotaOverage[];
  usage: Record<string, QuotaUsage>;
}

export interface QuotaResource {
  id: number;
  name: string;
  email?: string;
  role?: string;
  type?: string;
  duration?: number;
  price?: string;
  created_at: string | null;
  is_archived: boolean;
  archived_at: string | null;
}

export interface QuotaResourcesResponse {
  quota_type: string;
  resources: QuotaResource[];
}

export interface ArchiveResponse {
  archived_count: number;
  current_usage: number;
  limit: number;
  is_resolved: boolean;
}

export interface QuotaOverageDetail extends QuotaOverage {
  status: string;
  created_at: string;
  initial_email_sent_at: string | null;
  week_reminder_sent_at: string | null;
  day_reminder_sent_at: string | null;
  archived_resource_ids: number[];
}

/**
 * Get current quota status
 */
export const getQuotaStatus = async (): Promise<QuotaStatus> => {
  const response = await apiClient.get<QuotaStatus>('/quota/status/');
  return response.data;
};

/**
 * Get resources for a specific quota type
 */
export const getQuotaResources = async (quotaType: string): Promise<QuotaResourcesResponse> => {
  const response = await apiClient.get<QuotaResourcesResponse>(`/quota/resources/${quotaType}/`);
  return response.data;
};

/**
 * Archive resources to resolve quota overage
 */
export const archiveResources = async (
  quotaType: string,
  resourceIds: number[]
): Promise<ArchiveResponse> => {
  const response = await apiClient.post<ArchiveResponse>('/quota/archive/', {
    quota_type: quotaType,
    resource_ids: resourceIds,
  });
  return response.data;
};

/**
 * Unarchive a resource
 */
export const unarchiveResource = async (
  quotaType: string,
  resourceId: number
): Promise<{ success: boolean; resource_id: number }> => {
  const response = await apiClient.post('/quota/unarchive/', {
    quota_type: quotaType,
    resource_id: resourceId,
  });
  return response.data;
};

/**
 * Get details for a specific overage
 */
export const getOverageDetail = async (overageId: number): Promise<QuotaOverageDetail> => {
  const response = await apiClient.get<QuotaOverageDetail>(`/quota/overages/${overageId}/`);
  return response.data;
};
