import api from './api';
import type {
  BusinessProfile,
  MatchingRequest,
  MatchingResponse,
  BusinessSearch,
} from '../types/business';

export const businessService = {
  async getProfile(): Promise<BusinessProfile | null> {
    const response = await api.get('/api/businesses/profiles/');
    const data = response.data;
    // Handle both paginated {results: [...]} and plain array responses
    const list: BusinessProfile[] = Array.isArray(data) ? data : (data?.results ?? []);
    return list.length > 0 ? list[0] : null;
  },

  async createProfile(data: Partial<BusinessProfile>): Promise<BusinessProfile> {
    const response = await api.post<BusinessProfile>('/api/businesses/profiles/', data);
    return response.data;
  },

  async updateProfile(id: number, data: Partial<BusinessProfile>): Promise<BusinessProfile> {
    const response = await api.patch<BusinessProfile>(`/api/businesses/profiles/${id}/`, data);
    return response.data;
  },

  async matchInfluencers(request: MatchingRequest): Promise<MatchingResponse> {
    const response = await api.post<MatchingResponse>('/api/businesses/match/', request);
    return response.data;
  },

  async getSearchHistory(): Promise<BusinessSearch[]> {
    const response = await api.get<BusinessSearch[]>('/api/businesses/search-history/');
    return response.data;
  },
};
