/**
 * Admin API - API Keys Management
 */

import { api as client } from '../apiClient';

export interface AdminApiKey {
  id: string;
  name: string;
  provider: string;
  userId: string;
  username?: string;
  email?: string;
  maskedKey?: string;
  isActive?: boolean;
  createdAt: string;
  expiresAt?: string;
  usageCount?: number;
  lastUsedAt?: number;
}

export interface PaginationParams {
  page?: number;
  pageSize?: number;
}

export interface PaginationMeta {
  page: number;
  pageSize: number;
  total: number;
  totalPages: number;
}

export interface PaginatedResponse<T> {
  items: T[];
  page: number;
  pageSize: number;
  total: number;
  totalPages: number;
}

export interface ApiKeyListParams extends PaginationParams {
  search?: string;
  userId?: string;
  provider?: string;
}

export const listApiKeys = async (params: ApiKeyListParams): Promise<PaginatedResponse<AdminApiKey>> => {
  const response = await client.get('/api/admin/api-keys', { params });
  const { items, pagination } = response.data.data;
  return {
    items,
    ...pagination,
  };
};

export const getApiKey = async (id: string): Promise<AdminApiKey> => {
  const response = await client.get(`/api/admin/api-keys/${id}`);
  return response.data.data;
};

export const revokeApiKey = async (id: string): Promise<void> => {
  await client.delete(`/api/admin/api-keys/${id}`);
};

export interface ApiKeyUsageRecord {
  taskId?: string;
  taskType?: string;
  model?: string;
  createdAt?: string;
}

export interface ApiKeyUsage {
  records: ApiKeyUsageRecord[];
  usageCount?: number;
}

export const getApiKeyUsage = async (id: string): Promise<ApiKeyUsage> => {
  const response = await client.get(`/api/admin/api-keys/${id}/usage`);
  return response.data;
};
