import { StateMachine } from 'xstate';

// 商品状态定义
export type ProductState = 'draft' | 'pending_approval' | 'active' | 'inactive' | 'discontinued';

// 商品状态事件
export type ProductEvent = 
  | { type: 'SUBMIT_FOR_APPROVAL' }
  | { type: 'APPROVE' }
  | { type: 'REJECT' }
  | { type: 'ACTIVATE' }
  | { type: 'DEACTIVATE' }
  | { type: 'DISCONTINUE' }
  | { type: 'REACTIVATE' };

// 商品状态上下文
export interface ProductContext {
  productId: string;
  tenantId: string;
  shopId: string;
  taskId: string;
  traceId: string;
  businessType: 'TOC' | 'TOB';
  lastUpdated: string;
  updatedBy: string;
}

// 商品状态机
export const productStateMachine = StateMachine<ProductContext, ProductState, ProductEvent>({
  id: 'product',
  initial: 'draft',
  states: {
    draft: {
      on: {
        SUBMIT_FOR_APPROVAL: 'pending_approval'
      }
    },
    pending_approval: {
      on: {
        APPROVE: 'active',
        REJECT: 'draft'
      }
    },
    active: {
      on: {
        DEACTIVATE: 'inactive',
        DISCONTINUE: 'discontinued'
      }
    },
    inactive: {
      on: {
        ACTIVATE: 'active',
        DISCONTINUE: 'discontinued'
      }
    },
    discontinued: {
      on: {
        REACTIVATE: 'draft'
      }
    }
  }
});

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

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

  async transition(
    currentState: ProductState,
    event: ProductEvent,
    context: ProductContext
  ): Promise<{
    newState: ProductState;
    context: ProductContext;
  }> {
    const state = productStateMachine.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: ProductContext,
    fromState: ProductState,
    toState: ProductState
  ): void {
    console.log(`[ProductStateMachine] Product ${context.productId} transitioned from ${fromState} to ${toState}`, {
      ...context,
      fromState,
      toState,
      timestamp: new Date().toISOString()
    });
  }

  // 验证状态变更是否有效
  isValidTransition(fromState: ProductState, event: ProductEvent): boolean {
    const state = productStateMachine.transition(fromState, event);
    return state.value !== fromState || state.matches(fromState);
  }

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