import { http } from './client';
import type { PaginationParams } from './client';
import type {
  ProductionPlan,
  PlanProcessStep,
  YarnStock,
  InventoryRecord,
  Payment,
} from '../types';

// --- Plans ---

export interface TextilePlanDetail extends ProductionPlan {
  process_steps: PlanProcessStep[];
  purchaser_name: string;
}

// --- Dashboard ---

export interface TextileDashboardStats {
  total_plans: number;
  producing_plans: number;
  completed_plans: number;
  total_yarn_types: number;
  total_inventory_meters: number;
  pending_receivable: number;
}

export const textileApi = {
  // Dashboard
  dashboardStats: () =>
    http.get<TextileDashboardStats>('/textile/dashboard/stats').then(r => r.data),

  // Plans (read-only from textile perspective)
  listPlans: (params?: PaginationParams) =>
    http.get<TextilePlanDetail[]>('/textile/plans', params as Record<string, number>),

  getPlan: (id: string) =>
    http.get<TextilePlanDetail>(`/textile/plans/${id}`).then(r => r.data),

  // Process Steps
  completeStep: (planId: string, stepId: string, data?: { notes?: string; operator_name?: string }) =>
    http.post<PlanProcessStep>(`/textile/plans/${planId}/steps/${stepId}/complete`, data).then(r => r.data),

  rejectStep: (planId: string, stepId: string, data: { reason: string }) =>
    http.post<PlanProcessStep>(`/textile/plans/${planId}/steps/${stepId}/reject`, data).then(r => r.data),

  // Inventory
  inbound: (planId: string, data: { quantity: number; rolls?: number; notes?: string }) =>
    http.post<InventoryRecord>(`/textile/plans/${planId}/inventory`, data).then(r => r.data),

  listInventory: (planId: string) =>
    http.get<InventoryRecord[]>(`/textile/plans/${planId}/inventory`).then(r => r.data),

  // Yarn Stock
  listYarnStock: (params?: PaginationParams) =>
    http.get<YarnStock[]>('/textile/yarn-stock', params as Record<string, number>),

  createYarnStock: (data: Partial<YarnStock>) =>
    http.post<YarnStock>('/textile/yarn-stock', data).then(r => r.data),

  updateYarnStock: (id: string, data: Partial<YarnStock>) =>
    http.put<YarnStock>(`/textile/yarn-stock/${id}`, data).then(r => r.data),

  addYarnRecord: (id: string, data: { change_type: string; quantity: number; notes?: string }) =>
    http.post(`/textile/yarn-stock/${id}/records`, data),

  // Payments
  listPayments: (params?: PaginationParams) =>
    http.get<Payment[]>('/textile/payments', params as Record<string, number>),

  confirmPayment: (id: string) =>
    http.post<Payment>(`/textile/payments/${id}/confirm`).then(r => r.data),
};
