import { createMachine, createActor } 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 = createMachine({
  id: 'product',
  initial: 'draft',
  context: {} as ProductContext,
  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 newState = this.getNextState(currentState, event);
    
    const updatedContext = {
      ...context,
      lastUpdated: new Date().toISOString(),
    };

    this.logStateChange(updatedContext, currentState, newState);

    return {
      newState,
      context: updatedContext
    };
  }

  private getNextState(currentState: ProductState, event: ProductEvent): ProductState {
    const transitions: Record<ProductState, Partial<Record<ProductEvent['type'], ProductState>>> = {
      draft: { SUBMIT_FOR_APPROVAL: 'pending_approval' },
      pending_approval: { APPROVE: 'active', REJECT: 'draft' },
      active: { DEACTIVATE: 'inactive', DISCONTINUE: 'discontinued' },
      inactive: { ACTIVATE: 'active', DISCONTINUE: 'discontinued' },
      discontinued: { REACTIVATE: 'draft' }
    };
    
    return transitions[currentState]?.[event.type] || currentState;
  }

  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 newState = this.getNextState(fromState, event);
    return newState !== fromState;
  }

  getAvailableEvents(state: ProductState): ProductEvent['type'][] {
    const events: Record<ProductState, ProductEvent['type'][]> = {
      draft: ['SUBMIT_FOR_APPROVAL'],
      pending_approval: ['APPROVE', 'REJECT'],
      active: ['DEACTIVATE', 'DISCONTINUE'],
      inactive: ['ACTIVATE', 'DISCONTINUE'],
      discontinued: ['REACTIVATE']
    };
    return events[state] || [];
  }
}
