import { api } from './api';

export interface ProjectType {
  id: number;
  name: string;
}

export interface ProjectStatus {
  id: number;
  name: string;
  order?: number;
}

export interface Project {
  id: string;
  code: string;
  title: string;
  type_id: number;
  status_id: number;
  type?: ProjectType;
  status?: ProjectStatus;
  approved_estimate?: string | number | null;
  forecasted_effort?: Record<string, number> | null;
  created_at?: string;
  updated_at?: string;
}

export interface CreateProjectRequest {
  code: string;
  title: string;
  type_id: number;
}

export interface UpdateProjectRequest {
  code?: string;
  title?: string;
  type_id?: number;
  status_id?: number;
  approved_estimate?: number | null;
}

export const projectService = {
  /**
   * Get all projects
   */
  getAll: (statusId?: number, typeId?: number) => {
    const params = new URLSearchParams();
    if (statusId) params.append('status_id', String(statusId));
    if (typeId) params.append('type_id', String(typeId));
    const query = params.toString() ? `?${params.toString()}` : '';
    return api.get<Project[]>(`/projects${query}`);
  },

  /**
   * Get a single project by ID
   */
  getById: (id: string) => api.get<Project>(`/projects/${id}`),

  /**
   * Create a new project
   */
  create: (data: CreateProjectRequest) => api.post<Project>('/projects', data),

  /**
   * Update project basic info (code, title, type)
   */
  update: (id: string, data: UpdateProjectRequest) => 
    api.put<Project>(`/projects/${id}`, data),

  /**
   * Delete a project
   */
  delete: (id: string) => api.delete<{ message: string }>(`/projects/${id}`),

  /**
   * Transition project status
   */
  updateStatus: (id: string, statusId: number) => 
    api.put<Project>(`/projects/${id}/status`, { status_id: statusId }),

  /**
   * Set approved estimate
   */
  setEstimate: (id: string, estimate: number) => 
    api.put<Project>(`/projects/${id}/estimate`, { approved_estimate: estimate }),

  /**
   * Set forecasted effort
   */
  setForecast: (id: string, forecast: Record<string, number>) => 
    api.put<Project>(`/projects/${id}/forecast`, { forecasted_effort: forecast }),

  /**
   * Get all project types
   */
  getTypes: () => api.get<ProjectType[]>('/projects/types'),

  /**
   * Get all project statuses
   */
  getStatuses: () => api.get<ProjectStatus[]>('/projects/statuses'),
};

export default projectService;
