import { api } from '@services/api/axios-instance';
import type {
  Company,
  CreateCompanyDto,
  UpdateCompanyDto,
  CompanyFilters,
  CompaniesResponse,
} from '../types';

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

export const companiesApi = {
  // Get all companies with filters
  getAll: async (filters?: CompanyFilters): Promise<CompaniesResponse> => {
    const params = new URLSearchParams();
    if (filters?.search) params.append('search', filters.search);
    if (filters?.parentCompanyId) params.append('parentCompanyId', filters.parentCompanyId);
    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<CompaniesResponse>(`${BASE_URL}?${params.toString()}`);
    return response.data;
  },

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

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

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

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

  // Get child companies (subsidiaries)
  getChildren: async (parentId: string): Promise<Company[]> => {
    const response = await api.get<Company[]>(`${BASE_URL}/${parentId}/children`);
    return response.data;
  },
};
