/**
 * User API Keys
 */

import { api } from './apiClient';

export interface ApiKey {
  id: string;
  name: string;
  key: string;
  provider: string;
  isActive: boolean;
  created_at: string;
  expires_at?: string;
  maskedKey?: string;
  usageCount?: number;
  createdAt?: string;
  extraConfig?: Record<string, any>;
}

interface ResponseModel<T> {
  data: T;
}

export const listApiKeys = async (includeInactive: boolean = false): Promise<ApiKey[]> => {
  const response = await api.get<ResponseModel<ApiKey[]>>('/api/v1/user-api-keys', {
    params: { include_inactive: includeInactive }
  });
  return response.data.data;
};

export const createApiKey = async (data: {
  name?: string;
  provider: string;
  expires_at?: string;
  extraConfig?: Record<string, any>;
}): Promise<ApiKey> => {
  const response = await api.post<ResponseModel<ApiKey>>('/api/v1/user-api-keys', data);
  return response.data.data;
};

export const updateApiKey = async (
  id: string,
  data: { name?: string; enabled?: boolean }
): Promise<ApiKey> => {
  const response = await api.patch<ResponseModel<ApiKey>>(`/api/v1/user-api-keys/${id}`, data);
  return response.data.data;
};

export const deleteApiKey = async (id: string): Promise<void> => {
  await api.delete<ResponseModel<{ deleted: boolean; id: string }>>(`/api/v1/user-api-keys/${id}`);
};

export const verifyApiKey = async (id: string): Promise<{ valid: boolean; message: string }> => {
  const response = await api.post<ResponseModel<{ valid: boolean; message: string }>>(`/api/v1/user-api-keys/${id}/verify`);
  return response.data.data;
};
