import { apiClient } from '@/lib/api-client';
import type {
  MasterOptionCategoriesResponse,
  MasterOptionDetailResponse,
  MasterOptionMutationPayload,
  MasterOptionsFilters,
  MasterOptionsResponse,
  MutationSuccessResponse
} from './types';

const BASE_PATH = '/foundation/ms-options';

export async function getMasterOptions(filters: MasterOptionsFilters): Promise<MasterOptionsResponse> {
  const searchParams = new URLSearchParams();

  if (filters.page) searchParams.set('page', String(filters.page));
  if (filters.limit) searchParams.set('limit', String(filters.limit));
  if (filters.search) searchParams.set('search', filters.search);
  if (filters.category) searchParams.set('category', filters.category);
  if (filters.sort) searchParams.set('sort', filters.sort);

  const query = searchParams.toString();
  return apiClient<MasterOptionsResponse>(`${BASE_PATH}${query ? `?${query}` : ''}`);
}

export async function getMasterOptionById(id: string): Promise<MasterOptionDetailResponse> {
  return apiClient<MasterOptionDetailResponse>(`${BASE_PATH}/${id}`);
}

export async function createMasterOption(
  data: MasterOptionMutationPayload
): Promise<MutationSuccessResponse> {
  return apiClient<MutationSuccessResponse>(BASE_PATH, {
    method: 'POST',
    body: JSON.stringify(data)
  });
}

export async function updateMasterOption(
  id: string,
  data: Partial<MasterOptionMutationPayload>
): Promise<MutationSuccessResponse> {
  return apiClient<MutationSuccessResponse>(`${BASE_PATH}/${id}`, {
    method: 'PATCH',
    body: JSON.stringify(data)
  });
}

export async function deleteMasterOption(id: string): Promise<MutationSuccessResponse> {
  return apiClient<MutationSuccessResponse>(`${BASE_PATH}/${id}`, {
    method: 'DELETE'
  });
}

export async function getMasterOptionCategories(): Promise<MasterOptionCategoriesResponse> {
  return apiClient<MasterOptionCategoriesResponse>(`${BASE_PATH}/categories`);
}
