import { logger } from '../../utils/logger';
import db from '../../config/database';

export interface OnboardingStep {
  id: string;
  title: string;
  description: string;
  status: 'PENDING' | 'IN_PROGRESS' | 'COMPLETED' | 'SKIPPED';
  requiredAction?: string;
}

/**
 * [UX_START_01] 引导式新手任务看板 (Guided Onboarding Dashboard)
 * @description 核心逻辑：为新入驻商户提供阶梯式成长任务，
 * 从店铺授权、首个商品采集、首单履约等环节进行引导。
 * 通过任务激励（如 API 额度奖励）提升早期留存与业务跑通速度。
 */
export class OnboardingService {
  private static readonly ONBOARDING_TABLE = 'cf_tenant_onboarding';

  /**
   * 初始化表结构
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.ONBOARDING_TABLE);
    if (!hasTable) {
      console.log(`📦 Creating ${this.ONBOARDING_TABLE} table...`);
      await db.schema.createTable(this.ONBOARDING_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable().index();
        table.string('step_id', 64).notNullable();
        table.string('status', 16).defaultTo('PENDING');
        table.timestamp('completed_at');
        table.timestamps(true, true);
        table.unique(['tenant_id', 'step_id']);
      });
      console.log(`✅ Table ${this.ONBOARDING_TABLE} created`);
    }
  }

  /**
   * 获取租户新手任务列表
   */
  static async getOnboardingSteps(tenantId: string): Promise<OnboardingStep[]> {
    const defaultSteps: OnboardingStep[] = [
      { id: 'AUTH_STORE', title: '授权首个店铺', description: '连接您的 Shopify/TikTok 店铺以开启业务。', status: 'PENDING' },
      { id: 'QUICK_LIST', title: '极速刊登首个商品', description: '使用极速刊登功能从 1688/Amazon 导入商品。', status: 'PENDING' },
      { id: 'PRICING_RULE', title: '配置基础定价规则', description: '设置您的利润率红线与货币转换规则。', status: 'PENDING' },
      { id: 'FIRST_ORDER', title: '完成首单模拟履约', description: '体验从下单到发货的全流程。', status: 'PENDING' }
    ];

    const records = await db(this.ONBOARDING_TABLE).where({ tenant_id: tenantId });
    const recordMap = new Map(records.map(r => [r.step_id, r.status]));

    return defaultSteps.map(step => ({
      ...step,
      status: recordMap.get(step.id) || 'PENDING'
    }));
  }

  /**
   * 更新任务状态
   */
  static async updateStepStatus(tenantId: string, stepId: string, status: OnboardingStep['status']) {
    logger.info(`[Onboarding] Updating Step ${stepId} to ${status} for Tenant ${tenantId}`);

    await db(this.ONBOARDING_TABLE)
      .insert({
        tenant_id: tenantId,
        step_id: stepId,
        status: status,
        completed_at: status === 'COMPLETED' ? new Date() : null,
        updated_at: new Date()
      })
      .onConflict(['tenant_id', 'step_id'])
      .merge();
  }
}
