import { api } from './api';
import type {
  Actual,
  CreateActualRequest,
  UpdateActualRequest,
  ActualGridItem,
  ActualsPaginatedResponse,
  ActualsQueryParams
} from '$lib/types/actuals';

function buildQuery(month?: string, filters?: ActualsQueryParams): string {
  const params = new URLSearchParams();

  if (month) {
    params.set('month', month);
  }

  if (filters) {
    if (filters.page) {
      params.set('page', String(filters.page));
    }

    if (filters.per_page) {
      params.set('per_page', String(filters.per_page));
    }

    filters.project_ids?.forEach(id => {
      if (id) params.append('project_ids[]', id);
    });

    filters.team_member_ids?.forEach(id => {
      if (id) params.append('team_member_ids[]', id);
    });

    if (filters.include_inactive) {
      params.set('include_inactive', 'true');
    }

    if (filters.search) {
      params.set('search', filters.search);
    }
  }

  const query = params.toString();
  return query ? `?${query}` : '';
}

export const actualsService = {
  getAll: (month?: string, filters?: ActualsQueryParams) => {
    const query = buildQuery(month, filters);
    return api.get<ActualsPaginatedResponse<ActualGridItem[]>>(`/actuals${query}`, { unwrap: false });
  },

  getById: (id: string) => api.get<Actual>(`/actuals/${id}`),

  create: (data: CreateActualRequest) => api.post<Actual>('/actuals', data),

  update: (id: string, data: UpdateActualRequest) =>
    api.put<Actual>(`/actuals/${id}`, data),

  delete: (id: string) => api.delete<{ message: string }>(`/actuals/${id}`),
};

export default actualsService;
