import apiClient from './client'
import type { 
  MaterialAllocation, 
  CreateAllocationRequest, 
  AllocationDistribution,
  UpdateDistributionRequest,
  PaginatedResponse,
  PaginationParams 
} from '@/types'

export const allocationsApi = {
  async getAll(params?: PaginationParams): Promise<PaginatedResponse<MaterialAllocation>> {
    const response = await apiClient.get<PaginatedResponse<MaterialAllocation>>('/allocations', { params })
    return response.data
  },

  async getById(id: number): Promise<MaterialAllocation> {
    const response = await apiClient.get<MaterialAllocation>(`/allocations/${id}`)
    return response.data
  },

  async create(data: CreateAllocationRequest): Promise<MaterialAllocation> {
    const response = await apiClient.post<MaterialAllocation>('/allocations', data)
    return response.data
  },

  async update(id: number, data: Partial<CreateAllocationRequest>): Promise<MaterialAllocation> {
    const response = await apiClient.put<MaterialAllocation>(`/allocations/${id}`, data)
    return response.data
  },

  async delete(id: number): Promise<void> {
    await apiClient.delete(`/allocations/${id}`)
  },

  async getDistributions(allocationId: number): Promise<AllocationDistribution[]> {
    const response = await apiClient.get<AllocationDistribution[]>(`/allocations/${allocationId}/distribution`)
    return response.data
  },

  async updateDistribution(distributionId: number, data: UpdateDistributionRequest): Promise<AllocationDistribution> {
    const response = await apiClient.put<AllocationDistribution>(`/allocations/distributions/${distributionId}`, data)
    return response.data
  },

  async getMyDistributions(): Promise<AllocationDistribution[]> {
    const response = await apiClient.get<AllocationDistribution[]>('/allocations/my-distributions')
    return response.data
  },

  async getConsumptionReports(distributionId: number): Promise<ConsumptionReport[]> {
    const response = await apiClient.get<ConsumptionReport[]>(`/allocations/distributions/${distributionId}/reports`)
    return response.data
  },

  async getReportSummaryByUnit(distributionId: number): Promise<UnitReportSummary[]> {
    const response = await apiClient.get<UnitReportSummary[]>(`/allocations/distributions/${distributionId}/summary`)
    return response.data
  }
}

export interface ConsumptionReport {
  id: number
  reportedAmount: number
  cumulativeAmount: number
  remarks?: string
  reportedByUserName?: string
  reportedAt: string
}

export interface UnitReportSummary {
  unitId: number
  unitName: string
  unitLevel: string
  totalReported: number
  reportCount: number
  lastReportedAt?: string
}
