import { warehouseDataSource } from './warehouseDataSource';
import { OrderFulfillmentPlan, StockReservation } from '@/types/warehouse';

export interface OrderItem {
  order_id: string;
  order_item_id: string;
  sku: string;
  quantity: number;
  price: number;
}

export interface InventoryCheckResult {
  can_fulfill: boolean;
  items: {
    sku: string;
    requested: number;
    available: number;
    can_fulfill: boolean;
    message: string;
  }[];
  total_items: number;
  fulfillable_items: number;
}

class OrderInventoryService {
  async checkOrderInventory(items: OrderItem[]): Promise<InventoryCheckResult> {
    const results = await Promise.all(
      items.map(async (item) => {
        const availability = await warehouseDataSource.checkStockAvailability(
          item.sku,
          item.quantity
        );
        
        return {
          sku: item.sku,
          requested: item.quantity,
          available: availability.total_available,
          can_fulfill: availability.can_fulfill,
          message: availability.can_fulfill 
            ? `库存充足 (${availability.total_available} 可用)`
            : `库存不足 (需要 ${item.quantity}，可用 ${availability.total_available})`,
        };
      })
    );

    return {
      can_fulfill: results.every(r => r.can_fulfill),
      items: results,
      total_items: items.length,
      fulfillable_items: results.filter(r => r.can_fulfill).length,
    };
  }

  async reserveOrderInventory(orderId: string, items: OrderItem[]): Promise<{
    success: boolean;
    reservations: StockReservation[];
    failedItems: string[];
  }> {
    const checkResult = await this.checkOrderInventory(items);
    
    if (!checkResult.can_fulfill) {
      const failedItems = checkResult.items
        .filter(i => !i.can_fulfill)
        .map(i => i.sku);
      
      return {
        success: false,
        reservations: [],
        failedItems,
      };
    }

    const reservations = await warehouseDataSource.reserveStock(
      orderId,
      items.map(i => ({ salesSkuCode: i.sku, quantity: i.quantity }))
    );

    return {
      success: true,
      reservations,
      failedItems: [],
    };
  }

  async releaseOrderInventory(reservationIds: string[]): Promise<void> {
    await Promise.all(
      reservationIds.map(id => warehouseDataSource.releaseStock(id))
    );
  }

  async createFulfillmentPlan(orderId: string): Promise<OrderFulfillmentPlan> {
    return await warehouseDataSource.fulfillOrder(orderId);
  }

  async processOrderCreated(orderId: string, items: OrderItem[]): Promise<{
    status: 'RESERVED' | 'PARTIAL' | 'FAILED';
    message: string;
    reservations?: StockReservation[];
    failedItems?: string[];
  }> {
    const { success, reservations, failedItems } = await this.reserveOrderInventory(orderId, items);

    if (success) {
      return {
        status: 'RESERVED',
        message: '订单库存已预留',
        reservations,
      };
    }

    if (failedItems.length < items.length) {
      return {
        status: 'PARTIAL',
        message: `部分商品库存不足: ${failedItems.join(', ')}`,
        failedItems,
      };
    }

    return {
      status: 'FAILED',
      message: '所有商品库存不足',
      failedItems,
    };
  }

  async processOrderCancelled(orderId: string, reservationIds: string[]): Promise<void> {
    await this.releaseOrderInventory(reservationIds);
  }

  async processOrderShipped(orderId: string): Promise<OrderFulfillmentPlan> {
    return await this.createFulfillmentPlan(orderId);
  }
}

export const orderInventoryService = new OrderInventoryService();
