import apiClient from './authApi';

export type CodeType = 'HSN' | 'SAC';

export interface HsnSacCode {
  id: string;
  code: string;
  type: CodeType;
  gstRate?: number;
  description?: string;
  isActive: boolean;
  createdAt: string;
  updatedAt: string;
}

export interface CreateHsnSacCodeDTO {
  code: string;
  type: CodeType;
  gstRate?: number;
  description?: string;
  isActive?: boolean;
}

export interface HsnSacCodeResponse {
  codes: HsnSacCode[];
  pagination: {
    totalRecords: number;
    totalPages: number;
    currentPage: number;
    limit: number;
  };
}

/**
 * Get all HSN/SAC codes with pagination and search
 */
export async function getAllHsnSacCodes(
  onlyActive: boolean = false,
  page: number = 1,
  limit: number = 10,
  search?: string
): Promise<HsnSacCodeResponse> {
  const params: any = { active: onlyActive, page, limit };
  if (search) params.search = search;
  
  const response = await apiClient.get('/hsn-sac', { params });
  
  // Handle the standardized ResponseHandler format
  const data = response.data?.data;
  const pagination = response.data?.pagination;

  if (Array.isArray(data) && pagination) {
    return {
      codes: data,
      pagination
    };
  }

  // Fallback for unexpected formats
  return {
    codes: Array.isArray(data) ? data : [],
    pagination: pagination || { totalRecords: 0, totalPages: 0, currentPage: 1, limit: 10 }
  };
}

/**
 * Get code by ID
 */
export async function getHsnSacCodeById(id: string): Promise<HsnSacCode> {
  const response = await apiClient.get(`/hsn-sac/${id}`);
  return response.data?.data || response.data;
}

/**
 * Create new HSN/SAC code
 */
export async function createHsnSacCode(data: CreateHsnSacCodeDTO): Promise<HsnSacCode> {
  const response = await apiClient.post('/hsn-sac', data);
  return response.data?.data || response.data;
}

/**
 * Update HSN/SAC code
 */
export async function updateHsnSacCode(id: string, data: Partial<CreateHsnSacCodeDTO>): Promise<HsnSacCode> {
  const response = await apiClient.patch(`/hsn-sac/${id}`, data);
  return response.data?.data || response.data;
}

/**
 * Delete HSN/SAC code
 */
export async function deleteHsnSacCode(id: string): Promise<void> {
  await apiClient.delete(`/hsn-sac/${id}`);
}

/**
 * Toggle active status
 */
export async function toggleHsnSacCodeActive(id: string): Promise<HsnSacCode> {
  const response = await apiClient.patch(`/hsn-sac/${id}/toggle-active`);
  return response.data?.data || response.data;
}
