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

export interface ERPTask {
  id?: number;
  tenantId: string;
  sourceType: 'ORDER' | 'FINANCE' | 'INVENTORY' | 'SUPPLY_CHAIN';
  sourceId: string;
  taskType: string;
  priority: 'LOW' | 'MEDIUM' | 'HIGH' | 'URGENT';
  status: 'PENDING' | 'CLAIMED' | 'PROCESSING' | 'COMPLETED' | 'CANCELLED';
  assignedTo?: string; // User ID or Agent ID
  claimedAt?: Date;
  metadata: any;
  deadline?: Date;
}

/**
 * [ERP_TASK_01] 统一任务中枢与分发引擎 (Task Hub)
 * @description 核心逻辑：汇聚来自各业务领域的任务（如：待审核订单、待对账单、缺货预警），
 * 提供统一的任务池、认领机制与分发逻辑。支持人工与 AGI 协作处理。
 * 遵循 Autocomplete-First (V31.5) 规范。
 */
export class UnifiedTaskService {
  private static readonly TASK_TABLE = 'cf_unified_tasks';

  /**
   * 初始化表结构
   */
  static async initTable() {
    const hasTable = await db.schema.hasTable(this.TASK_TABLE);
    if (!hasTable) {
      logger.info(`📦 Creating ${this.TASK_TABLE} table...`);
      await db.schema.createTable(this.TASK_TABLE, (table) => {
        table.increments('id').primary();
        table.string('tenant_id', 64).index();
        table.string('source_type', 32).index();
        table.string('source_id', 64).index();
        table.string('task_type', 64);
        table.string('priority', 16).defaultTo('MEDIUM');
        table.string('status', 16).defaultTo('PENDING').index();
        table.string('assigned_to', 64).index();
        table.timestamp('claimed_at');
        table.json('metadata');
        table.timestamp('deadline');
        table.timestamps(true, true);

        table.index(['tenant_id', 'status', 'priority']);
      });
      logger.info(`✅ Table ${this.TASK_TABLE} created`);
    }
  }

  /**
   * 创建新任务 (Task Ingestion)
   */
  static async createTask(task: Omit<ERPTask, 'id' | 'status' | 'createdAt' | 'updatedAt'>) {
    logger.info(`[TaskHub] Creating task: ${task.taskType} from ${task.sourceType}:${task.sourceId}`);
    
    return await db(this.TASK_TABLE).insert({
      tenant_id: task.tenantId,
      source_type: task.sourceType,
      source_id: task.sourceId,
      task_type: task.taskType,
      priority: task.priority,
      status: 'PENDING',
      metadata: JSON.stringify(task.metadata),
      deadline: task.deadline
    });
  }

  /**
   * 认领任务 (Task Claiming)
   */
  static async claimTask(taskId: number, userId: string): Promise<boolean> {
    logger.info(`[TaskHub] User ${userId} claiming task ${taskId}`);
    
    const updated = await db(this.TASK_TABLE)
      .where({ id: taskId, status: 'PENDING' })
      .update({
        assigned_to: userId,
        status: 'CLAIMED',
        claimed_at: new Date(),
        updated_at: new Date()
      });
    
    return updated > 0;
  }

  /**
   * 完成任务
   */
  static async completeTask(taskId: number, resultMetadata?: any) {
    logger.info(`[TaskHub] Task ${taskId} completed.`);
    
    await db(this.TASK_TABLE)
      .where({ id: taskId })
      .update({
        status: 'COMPLETED',
        metadata: resultMetadata ? JSON.stringify(resultMetadata) : undefined,
        updated_at: new Date()
      });
  }

  /**
   * 获取租户待办任务池 (Pending Task Pool)
   */
  static async getPendingTasks(tenantId: string) {
    return await db(this.TASK_TABLE)
      .where({ tenant_id: tenantId, status: 'PENDING' })
      .orderByRaw("CASE priority WHEN 'URGENT' THEN 1 WHEN 'HIGH' THEN 2 WHEN 'MEDIUM' THEN 3 ELSE 4 END")
      .orderBy('created_at', 'asc');
  }
}
