import { createMachine, createActor } from 'xstate';

// 订单状态定义
export type OrderState = 'pending' | 'paid' | 'split' | 'processing' | 'shipped' | 'completed' | 'refunded' | 'cancelled';

// 订单状态事件
export type OrderEvent = 
  | { type: 'PAY' }
  | { type: 'SPLIT' }
  | { type: 'PROCESS' }
  | { type: 'SHIP' }
  | { type: 'COMPLETE' }
  | { type: 'REFUND' }
  | { type: 'CANCEL' };

// 订单状态上下文
export interface OrderContext {
  orderId: string;
  tenantId: string;
  shopId: string;
  taskId: string;
  traceId: string;
  businessType: 'TOC' | 'TOB';
  lastUpdated: string;
  updatedBy: string;
  amount: number;
  customerId: string;
}

// 订单状态机
export const orderStateMachine = createMachine({
  id: 'order',
  initial: 'pending',
  context: {} as OrderContext,
  states: {
    pending: {
      on: {
        PAY: 'paid',
        CANCEL: 'cancelled'
      }
    },
    paid: {
      on: {
        SPLIT: 'split',
        PROCESS: 'processing',
        REFUND: 'refunded',
        CANCEL: 'cancelled'
      }
    },
    split: {
      on: {
        PROCESS: 'processing'
      }
    },
    processing: {
      on: {
        SHIP: 'shipped',
        REFUND: 'refunded',
        CANCEL: 'cancelled'
      }
    },
    shipped: {
      on: {
        COMPLETE: 'completed',
        REFUND: 'refunded'
      }
    },
    completed: {
      on: {
        REFUND: 'refunded'
      }
    },
    refunded: {
      type: 'final'
    },
    cancelled: {
      type: 'final'
    }
  }
});

// 状态变更服务
export class OrderStateMachineService {
  private static instance: OrderStateMachineService;

  static getInstance(): OrderStateMachineService {
    if (!OrderStateMachineService.instance) {
      OrderStateMachineService.instance = new OrderStateMachineService();
    }
    return OrderStateMachineService.instance;
  }

  async transition(
    currentState: OrderState,
    event: OrderEvent,
    context: OrderContext
  ): Promise<{
    newState: OrderState;
    context: OrderContext;
  }> {
    const newState = this.getNextState(currentState, event);
    
    const updatedContext = {
      ...context,
      lastUpdated: new Date().toISOString(),
    };

    this.logStateChange(updatedContext, currentState, newState);

    return {
      newState,
      context: updatedContext
    };
  }

  private getNextState(currentState: OrderState, event: OrderEvent): OrderState {
    const transitions: Record<OrderState, Partial<Record<OrderEvent['type'], OrderState>>> = {
      pending: { PAY: 'paid', CANCEL: 'cancelled' },
      paid: { SPLIT: 'split', PROCESS: 'processing', REFUND: 'refunded', CANCEL: 'cancelled' },
      split: { PROCESS: 'processing' },
      processing: { SHIP: 'shipped', REFUND: 'refunded', CANCEL: 'cancelled' },
      shipped: { COMPLETE: 'completed', REFUND: 'refunded' },
      completed: { REFUND: 'refunded' },
      refunded: {},
      cancelled: {}
    };
    
    return transitions[currentState]?.[event.type] || currentState;
  }

  private logStateChange(
    context: OrderContext,
    fromState: OrderState,
    toState: OrderState
  ): void {
    console.log(`[OrderStateMachine] Order ${context.orderId} transitioned from ${fromState} to ${toState}`, {
      ...context,
      fromState,
      toState,
      timestamp: new Date().toISOString()
    });
  }

  isValidTransition(fromState: OrderState, event: OrderEvent): boolean {
    const newState = this.getNextState(fromState, event);
    return newState !== fromState;
  }

  getAvailableEvents(state: OrderState): OrderEvent['type'][] {
    const events: Record<OrderState, OrderEvent['type'][]> = {
      pending: ['PAY', 'CANCEL'],
      paid: ['SPLIT', 'PROCESS', 'REFUND', 'CANCEL'],
      split: ['PROCESS'],
      processing: ['SHIP', 'REFUND', 'CANCEL'],
      shipped: ['COMPLETE', 'REFUND'],
      completed: ['REFUND'],
      refunded: [],
      cancelled: []
    };
    return events[state] || [];
  }
}
