import { apiClient } from '@/lib/api-client';
import type {
  TrainingPolicyByIdResponse,
  TrainingPolicyFilters,
  TrainingPolicyHistoryResponse,
  TrainingPolicyMutationPayload,
  TrainingPoliciesResponse
} from './types';

function createQueryString<T extends object>(filters: T) {
  const params = new URLSearchParams();

  for (const [key, value] of Object.entries(filters as Record<string, unknown>)) {
    if (value !== undefined && value !== null && value !== '') {
      params.set(key, String(value));
    }
  }

  return params.toString();
}

export async function getTrainingPolicies(
  filters: TrainingPolicyFilters
): Promise<TrainingPoliciesResponse> {
  const queryString = createQueryString(filters);
  return apiClient<TrainingPoliciesResponse>(
    `/training-policies${queryString ? `?${queryString}` : ''}`
  );
}

export async function getTrainingPolicy(id: number): Promise<TrainingPolicyByIdResponse> {
  return apiClient<TrainingPolicyByIdResponse>(`/training-policies/${id}`);
}

export async function createTrainingPolicy(data: TrainingPolicyMutationPayload) {
  return apiClient<TrainingPolicyByIdResponse>('/training-policies', {
    method: 'POST',
    body: JSON.stringify(data)
  });
}

export async function updateTrainingPolicy(id: number, data: TrainingPolicyMutationPayload) {
  return apiClient<TrainingPolicyByIdResponse>(`/training-policies/${id}`, {
    method: 'PATCH',
    body: JSON.stringify(data)
  });
}

export async function cloneTrainingPolicy(id: number) {
  return apiClient<{ success: boolean; message: string; policy_id: number }>(
    `/training-policies/${id}/clone`,
    {
      method: 'POST'
    }
  );
}

export async function activateTrainingPolicy(id: number) {
  return apiClient<{ success: boolean; message: string }>(`/training-policies/${id}/activate`, {
    method: 'POST'
  });
}

export async function deactivateTrainingPolicy(id: number) {
  return apiClient<{ success: boolean; message: string }>(`/training-policies/${id}/deactivate`, {
    method: 'POST'
  });
}

export async function getTrainingPolicyHistory(id: number): Promise<TrainingPolicyHistoryResponse> {
  return apiClient<TrainingPolicyHistoryResponse>(`/training-policies/${id}/history`);
}
