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

export interface DeliveryItem {
  id: string;
  category: 'INFRA' | 'SECURITY' | 'COMPLIANCE' | 'BIZ';
  title: string;
  description: string;
  isMandatory: boolean;
}

export interface DeliveryPlan {
  type: 'SaaS' | 'Private' | 'Hybrid';
  name: string;
  items: DeliveryItem[];
}

/**
 * [BIZ_TEN_03] 多租户标准交付与流程自动化 (Delivery)
 * @description 形成 SaaS / 专有化 / 混合部署三套标准交付清单，并追踪自动化开通流程。
 */
export class DeliveryTemplateService {
  private static readonly TABLE_NAME = 'cf_delivery_tasks';

  private static readonly PLANS: Record<string, DeliveryPlan> = {
    'SaaS': {
      type: 'SaaS',
      name: 'Standard SaaS Delivery',
      items: [
        { id: 'S1', category: 'INFRA', title: 'Tenant Provisioning', description: 'Create tenant isolation context', isMandatory: true },
        { id: 'S2', category: 'SECURITY', title: 'User SSO Link', description: 'Link user to existing SSO if available', isMandatory: false }
      ]
    },
    'Private': {
      type: 'Private',
      name: 'Private Cloud Deployment',
      items: [
        { id: 'P1', category: 'INFRA', title: 'Isolated Database', description: 'Dedicated RDS instance setup', isMandatory: true },
        { id: 'P2', category: 'SECURITY', title: 'Enterprise SSO Integration', description: 'OIDC/SAML integration with enterprise IDP', isMandatory: true },
        { id: 'P3', category: 'COMPLIANCE', title: 'Audit Log Export', description: 'Push logs to enterprise SIEM', isMandatory: true }
      ]
    },
    'Hybrid': {
      type: 'Hybrid',
      name: 'Hybrid Node Execution',
      items: [
        { id: 'H1', category: 'INFRA', title: 'Local Node Gateway', description: 'Setup on-prem Win Node gateway', isMandatory: true },
        { id: 'H2', category: 'BIZ', title: 'Custom FX Strategy', description: 'Link to enterprise treasury rates', isMandatory: false }
      ]
    }
  };

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.TABLE_NAME);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.TABLE_NAME} table...`);
      await db.schema.createTable(this.TABLE_NAME, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).notNullable().index();
        table.string('plan_type', 32).notNullable();
        table.string('item_id', 32).notNullable();
        table.string('category', 32);
        table.string('title', 128);
        table.string('status', 32).defaultTo('PENDING'); // PENDING, IN_PROGRESS, COMPLETED, FAILED
        table.text('error_message');
        table.json('metadata');
        table.timestamps(true, true);

        table.unique(['tenant_id', 'item_id']);
      });
      logger.info(`✅ Table ${this.TABLE_NAME} created`);
    }
  }

  /**
   * 获取交付模板计划
   */
  static getPlan(type: 'SaaS' | 'Private' | 'Hybrid'): DeliveryPlan {
    logger.info(`[Delivery] Fetching delivery plan for: ${type}`);
    return this.PLANS[type];
  }

  /**
   * 启动交付流程 (V30.0 BIZ_TEN_03)
   */
  static async startDelivery(tenantId: string, type: 'SaaS' | 'Private' | 'Hybrid'): Promise<void> {
    const plan = this.getPlan(type);
    logger.info(`[Delivery] Starting delivery ${plan.name} for Tenant: ${tenantId}`);
    
    // 1. 初始化所有交付项为 PENDING
    const tasks = plan.items.map(item => ({
      tenant_id: tenantId,
      plan_type: type,
      item_id: item.id,
      category: item.category,
      title: item.title,
      status: 'PENDING',
      created_at: new Date(),
      updated_at: new Date()
    }));

    await db(this.TABLE_NAME).insert(tasks).onConflict(['tenant_id', 'item_id']).ignore();

    // 2. 触发自动化开通流程 (示例：SaaS 模式自动完成 S1)
    if (type === 'SaaS') {
      await this.updateTaskStatus(tenantId, 'S1', 'COMPLETED', { auto: true });
    }
  }

  /**
   * 更新交付任务状态
   */
  static async updateTaskStatus(tenantId: string, itemId: string, status: 'PENDING' | 'IN_PROGRESS' | 'COMPLETED' | 'FAILED', metadata?: any) {
    logger.info(`[Delivery] Updating task ${itemId} for tenant ${tenantId} to ${status}`);
    
    await db(this.TABLE_NAME)
      .where({ tenant_id: tenantId, item_id: itemId })
      .update({
        status,
        metadata: metadata ? JSON.stringify(metadata) : null,
        updated_at: new Date()
      });
  }

  /**
   * 获取租户交付进度
   */
  static async getDeliveryProgress(tenantId: string) {
    const tasks = await db(this.TABLE_NAME).where({ tenant_id: tenantId });
    if (tasks.length === 0) return null;

    const completed = tasks.filter(t => t.status === 'COMPLETED').length;
    const total = tasks.length;

    return {
      tenantId,
      planType: tasks[0].plan_type,
      progress: Number(((completed / total) * 100).toFixed(2)),
      tasks: tasks.map(t => ({
        id: t.item_id,
        title: t.title,
        category: t.category,
        status: t.status,
        updatedAt: t.updated_at
      }))
    };
  }
}
