import { api } from '@services/api/axios-instance';
import type {
  Partner,
  CreatePartnerDto,
  UpdatePartnerDto,
  PartnerFilters,
  PartnersResponse,
} from '../types';

const BASE_URL = '/api/v1/partners';

export const partnersApi = {
  // Get all partners with filters
  getAll: async (filters?: PartnerFilters): Promise<PartnersResponse> => {
    const params = new URLSearchParams();
    if (filters?.search) params.append('search', filters.search);
    if (filters?.partnerType) params.append('partnerType', filters.partnerType);
    if (filters?.isCustomer !== undefined) params.append('isCustomer', String(filters.isCustomer));
    if (filters?.isSupplier !== undefined) params.append('isSupplier', String(filters.isSupplier));
    if (filters?.active !== undefined) params.append('active', String(filters.active));
    if (filters?.page) params.append('page', String(filters.page));
    if (filters?.limit) params.append('limit', String(filters.limit));
    if (filters?.sortBy) params.append('sortBy', filters.sortBy);
    if (filters?.sortOrder) params.append('sortOrder', filters.sortOrder);

    const response = await api.get<PartnersResponse>(`${BASE_URL}?${params.toString()}`);
    return response.data;
  },

  // Get partner by ID
  getById: async (id: string): Promise<Partner> => {
    const response = await api.get<Partner>(`${BASE_URL}/${id}`);
    return response.data;
  },

  // Create partner
  create: async (data: CreatePartnerDto): Promise<Partner> => {
    const response = await api.post<Partner>(BASE_URL, data);
    return response.data;
  },

  // Update partner
  update: async (id: string, data: UpdatePartnerDto): Promise<Partner> => {
    const response = await api.patch<Partner>(`${BASE_URL}/${id}`, data);
    return response.data;
  },

  // Delete partner
  delete: async (id: string): Promise<void> => {
    await api.delete(`${BASE_URL}/${id}`);
  },

  // Get customers only
  getCustomers: async (filters?: PartnerFilters): Promise<PartnersResponse> => {
    return partnersApi.getAll({ ...filters, isCustomer: true });
  },

  // Get suppliers only
  getSuppliers: async (filters?: PartnerFilters): Promise<PartnersResponse> => {
    return partnersApi.getAll({ ...filters, isSupplier: true });
  },

  // Activate partner
  activate: async (id: string): Promise<Partner> => {
    const response = await api.post<Partner>(`${BASE_URL}/${id}/activate`);
    return response.data;
  },

  // Deactivate partner
  deactivate: async (id: string): Promise<Partner> => {
    const response = await api.post<Partner>(`${BASE_URL}/${id}/deactivate`);
    return response.data;
  },
};
