import { http } from './client';
import type { PaginationParams, ApiResponse } from './client';
import type {
  ProductionPlan,
  PlanFactory,
  YarnRatio,
  PlanProcessStep,
  Product,
  WashingPlan,
  Company,
} from '../types';
import type { ProductPriceHistory, ProductInRecord } from '../types';

// --- Plans ---

export interface PlanDetail extends ProductionPlan {
  process_steps: PlanProcessStep[];
  inventory_records: { time: string; quantity: number; rolls: number | null }[];
  price_history?: ProductPriceHistory[];
  yarn_ratios?: YarnRatio[];
  image_url?: string | null;
  warp_weight?: number | null;
  weft_weight?: number | null;
  total_weight?: number | null;
}

export interface PlanListResponse {
  plans: PlanDetail[];
  factories: Company[];
  plan_factories: PlanFactory[];
  operator_names: Record<string, string>;
}

export interface CreatePlanRequest {
  product_name: string;
  fabric_code: string;
  color_code: string;
  color: string;
  target_quantity: number;
  unit_price?: number;
  notes?: string;
  yarn_ratios?: { yarn_name: string; ratio: number; amount_per_meter?: number; yarn_type?: string }[];
}

// --- Products ---

export interface InboundRequest {
  batch_no: string;
  rolls: number;
  meters: number;
  notes?: string;
  warehouse_id?: string;
  plan_code?: string;
  factory_id?: string;
  source?: 'self' | 'textile';
  price_per_meter?: number;
}

export interface OutboundRequest {
  batch_no: string;
  rolls: number;
  meters: number;
  outbound_type: string;
  notes?: string;
  washing_plan_id?: string;
  recipient_company_id?: string;
}

// --- Dashboard ---

export interface DashboardStats {
  total_plans: number;
  producing_plans: number;
  completed_plans: number;
  total_products: number;
  total_stock_meters: number;
  pending_payable: number;
}

export const purchaserApi = {
  // Dashboard
  dashboardStats: () =>
    http.get<DashboardStats>('/purchaser/dashboard/stats').then(r => r.data),

  // Plans
  listPlans: (params?: PaginationParams) =>
    http.get<PlanListResponse>('/purchaser/plans', params as Record<string, number>),

  createPlan: (data: CreatePlanRequest) =>
    http.post<ProductionPlan>('/purchaser/plans', data).then(r => r.data),

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

  updatePlan: (id: string, data: Partial<CreatePlanRequest>) =>
    http.put<ProductionPlan>(`/purchaser/plans/${id}`, data).then(r => r.data),

  deletePlan: (id: string) =>
    http.delete(`/purchaser/plans/${id}`),

  assignFactory: (planId: string, data: { factory_id: string; factory_type: string }) =>
    http.post<PlanFactory>(`/purchaser/plans/${planId}/factories`, data).then(r => r.data),

  getPlanSteps: (planId: string) =>
    http.get<PlanProcessStep[]>(`/purchaser/plans/${planId}/steps`).then(r => r.data),

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

  // Products
  listProducts: (params?: PaginationParams) =>
    http.get<Product[]>('/purchaser/products', params as Record<string, number>),

  createProduct: (data: Record<string, unknown>) =>
    http.post<Product>('/purchaser/products', data).then(r => r.data),

  updateProduct: (id: string, data: Record<string, unknown>) =>
    http.put<Product>(`/purchaser/products/${id}`, data).then(r => r.data),

  deleteProduct: (id: string) =>
    http.delete(`/purchaser/products/${id}`),

  inbound: (productId: string, data: InboundRequest) =>
    http.post<ProductInRecord>(`/purchaser/products/${productId}/inbound`, data).then(r => r.data),

  outbound: (productId: string, data: OutboundRequest) =>
    http.post<ProductInRecord>(`/purchaser/products/${productId}/outbound`, data).then(r => r.data),

  getRecords: (productId: string) =>
    http.get<ProductInRecord[]>(`/purchaser/products/${productId}/records`).then(r => r.data),

  updatePrice: (productId: string, data: { price: number; reason?: string }) =>
    http.put(`/purchaser/products/${productId}/price`, data),

  priceHistory: (productId: string) =>
    http.get<ProductPriceHistory[]>(`/purchaser/products/${productId}/price-history`).then(r => r.data),

  // Factories
  listFactories: () =>
    http.get<Company[]>('/purchaser/factories').then(r => r.data),

  // Accounts Payable
  listAccountsPayable: (params?: PaginationParams) =>
    http.get<unknown[]>('/purchaser/accounts-payable', params as Record<string, number>),

  payAccountsPayable: (id: string, data: { amount: number; notes?: string }) =>
    http.post(`/purchaser/accounts-payable/${id}/pay`, data),

  // Washing Plans
  createWashingPlan: (data: Partial<WashingPlan>) =>
    http.post<WashingPlan>('/purchaser/washing-plans', data).then(r => r.data),

  listWashingPlans: (params?: PaginationParams) =>
    http.get<WashingPlan[]>('/purchaser/washing-plans', params as Record<string, number>),
};
