/**
 * Allocation Service
 *
 * API operations for resource allocation management.
 */

import { api } from './api';

export type VarianceStatus = 'OVER' | 'UNDER' | 'MATCH' | null;

export interface RowVariance {
  allocated_total: number;
  planned_month: number;
  variance: number;
  status: VarianceStatus;
}

export interface ColumnVariance {
  allocated: number;
  capacity: number;
  variance: number;
  status: VarianceStatus;
}

export interface Allocation {
  id: string;
  project_id: string;
  team_member_id: string | null;
  month: string;
  allocated_hours: string;
  is_untracked?: boolean;
  row_variance?: RowVariance;
  column_variance?: ColumnVariance | null;
  allocation_indicator?: 'green' | 'yellow' | 'red' | 'gray';
  warnings?: string[];
  utilization?: number;
  created_at: string;
  updated_at: string;
  project?: {
    id: string;
    code: string;
    title: string;
  };
  team_member?: {
    id: string;
    name: string;
  } | null;
}

export interface CreateAllocationRequest {
  project_id: string;
  team_member_id: string | null;
  month: string;
  allocated_hours: number;
}

export interface UpdateAllocationRequest {
  allocated_hours: number;
}

export interface BulkAllocationRequest {
  allocations: CreateAllocationRequest[];
}

export interface BulkAllocationResponse {
  data: Array<{ index: number; id: string; status: string }>;
  failed: Array<{ index: number; errors: Record<string, string[]> }>;
  summary: { created: number; failed: number };
}

// Allocation API methods
export const allocationService = {
  /**
   * Get all allocations, optionally filtered by month
   */
  getAll: (month?: string) => {
    const query = month ? `?month=${month}` : '';
    return api.get<Allocation[]>(`/allocations${query}`);
  },

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

  /**
   * Create a new allocation
   */
  create: (data: CreateAllocationRequest) => api.post<Allocation>('/allocations', data),

  /**
   * Update an existing allocation
   */
  update: (id: string, data: UpdateAllocationRequest) =>
    api.put<Allocation>(`/allocations/${id}`, data),

  /**
   * Delete an allocation
   */
  delete: (id: string) => api.delete<{ message: string }>(`/allocations/${id}`),

  /**
   * Bulk create allocations
   */
  bulkCreate: (data: BulkAllocationRequest) =>
    api.post<BulkAllocationResponse>('/allocations/bulk', data),
};

/**
 * Format allocated hours
 */
export function formatAllocatedHours(hours: string | number): string {
  const numHours = typeof hours === 'string' ? parseFloat(hours) : hours;
  return `${numHours}h`;
}

export default allocationService;
