import { create } from 'zustand';
import { api } from '../../services/api';

interface ChatRequestData {
  data: string;
  responseFormat?: 'text' | 'json';
  model?: string;
}

type ChatStore = {
  sendChatRequest: (endpoint: string, data: ChatRequestData) => Promise<any>;
};

export const useChatStore = create<ChatStore>(() => ({
  sendChatRequest: async (endpoint, requestData) => {
    try {
      if (
        !requestData.data ||
        typeof requestData.data !== 'string' ||
        requestData.data.trim() === ''
      ) {
        throw new Error("Invalid input: 'data' must be a non-empty string.");
      }

      const formattedRequest = {
        data: requestData.data,
        model: requestData.model || 'gpt-4-mini',
        response_format: requestData.responseFormat === 'json' ? { type: 'json_object' } : undefined
      };

      console.log('Sending formatted request:', formattedRequest);
      const response = await api('post', endpoint, formattedRequest, undefined, 'json', 60, true);
      console.log('Got API response:', response);

      if (!response || !response.data) {
        throw new Error('Invalid response from server');
      }

      return response.data;
    } catch (error) {
      console.error(`Failed to send chat request to ${endpoint}:`, error);
      throw error;
    }
  },
}));
