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

export interface CustomerProfile {
  id: string;
  tenantId: string;
  name: string;
  email: string;
  phone?: string;
  level: 'BRONZE' | 'SILVER' | 'GOLD' | 'PLATINUM';
  totalOrders: number;
  totalSpent: number;
  creditScore: number;
  tags: string[];
}

/**
 * [ERP_CRM_01] 客户 360 视图与商机中枢 (CRM Hub)
 * @description 核心逻辑：聚合订单历史、客诉记录、财务往来与信用分，提供全生命周期客户档案。
 */
export class Customer360Service {
  private static readonly TABLE_NAME = 'cf_customer_profiles';

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const exists = await db.schema.hasTable(this.TABLE_NAME);
    if (!exists) {
      logger.info(`📦 Creating ${this.TABLE_NAME} table...`);
      await db.schema.createTable(this.TABLE_NAME, (table) => {
        table.string('id', 64).primary();
        table.string('tenant_id', 64).notNullable();
        table.string('name', 128).notNullable();
        table.string('email', 128).notNullable();
        table.string('phone', 32);
        table.string('level', 32).defaultTo('BRONZE');
        table.integer('total_orders').defaultTo(0);
        table.decimal('total_spent', 15, 2).defaultTo(0);
        table.integer('credit_score').defaultTo(100);
        table.json('tags');
        table.timestamps(true, true);

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

  /**
   * [ERP_CRM_01] 获取客户 360 视图 (Get Customer 360 View)
   */
  static async getCustomer360(tenantId: string, customerId: string) {
    logger.info(`[CRM] Fetching 360 view for Customer: ${customerId}`);

    // 1. 获取基础档案
    const profile = await db(this.TABLE_NAME).where({ id: customerId, tenant_id: tenantId }).first();
    if (!profile) throw new Error('Customer profile not found');

    // 2. 聚合订单历史 (ToC)
    const orders = await db('cf_consumer_orders')
      .where({ tenant_id: tenantId, customer_name: profile.name }) // 假设按名称匹配，实际应按 ID
      .orderBy('created_at', 'desc')
      .limit(10);

    // 3. 聚合财务往来
    const transactions = await db('cf_finance_reconciliation')
      .join('cf_consumer_orders', 'cf_finance_reconciliation.order_id', 'cf_consumer_orders.id')
      .where('cf_consumer_orders.customer_name', profile.name)
      .select('cf_finance_reconciliation.*')
      .limit(5);

    // 4. 聚合客诉争议
    const disputes = await db('cf_dispute_arbitration')
      .where({ tenant_id: tenantId, resource_id: customerId }) // 假设 resource_id 是 customerId
      .limit(5);

    return {
      profile: {
        ...profile,
        tags: profile.tags ? JSON.parse(profile.tags) : []
      },
      orders,
      transactions,
      disputes,
      summary: {
        lastOrderDate: orders[0]?.created_at,
        activeDisputes: disputes.filter(d => d.status === 'PENDING').length,
        reliability: profile.credit_score > 80 ? 'HIGH' : 'MEDIUM'
      }
    };
  }

  /**
   * [ERP_CRM_01] 更新客户信用分 (Update Credit Score)
   */
  static async updateCreditScore(tenantId: string, customerId: string, delta: number) {
    await db(this.TABLE_NAME)
      .where({ id: customerId, tenant_id: tenantId })
      .increment('credit_score', delta);
  }
}
