import { apiClient } from './apiClient';
import { ModelConfig } from '../types'; // Frontend ModelConfig interface

interface ModelConfigResponse extends Omit<ModelConfig, 'apiKey'> {
  // Backend response might omit apiKey for security
  id: string; // Ensure id is always present
  createdAt: Date;
  updatedAt: Date;
}

export const modelConfigService = {
  async getAll(token: string): Promise<ModelConfigResponse[]> {
    const response = await apiClient.request('/models', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    });
    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.message || 'Failed to fetch model configs');
    }
    return response.json();
  },

  async create(token: string, modelConfig: Omit<ModelConfig, 'id'>): Promise<ModelConfigResponse> {
    const response = await apiClient.request('/models', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(modelConfig),
    });
    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.message || 'Failed to create model config');
    }
    return response.json();
  },

  async update(token: string, id: string, modelConfig: Partial<Omit<ModelConfig, 'id'>>): Promise<ModelConfigResponse> {
    const response = await apiClient.request(`/models/${id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(modelConfig),
    });
    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.message || 'Failed to update model config');
    }
    return response.json();
  },

  async remove(token: string, id: string): Promise<void> {
    const response = await apiClient.request(`/models/${id}`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
      },
    });
    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.message || 'Failed to delete model config');
    }
  },

  async setDefault(token: string, id: string): Promise<ModelConfigResponse> {
    const response = await apiClient.request(`/models/${id}/set-default`, {
      method: 'PATCH',
      headers: {
        'Content-Type': 'application/json',
      },
    });
    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.message || 'Failed to set default model');
    }
    return response.json();
  },
};
