import { StateMachine } 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 = StateMachine<OrderContext, OrderState, OrderEvent>({
  id: 'order',
  initial: 'pending',
  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 state = orderStateMachine.transition(currentState, event);
    
    // 更新上下文
    const updatedContext = {
      ...context,
      lastUpdated: new Date().toISOString(),
    };

    // 记录状态变更日志
    this.logStateChange(updatedContext, currentState, state.value);

    return {
      newState: state.value,
      context: updatedContext
    };
  }

  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 state = orderStateMachine.transition(fromState, event);
    return state.value !== fromState || state.matches(fromState);
  }

  // 获取当前状态下可执行的事件
  getAvailableEvents(state: OrderState): OrderEvent['type'][] {
    const stateNode = orderStateMachine.getStateNode(state);
    return Object.keys(stateNode.on || {});
  }
}
