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

export interface CustomsData {
  tenantId: string;
  orderId: string;
  hscode: string;
  declaredValue: number;
  currency: string;
}

/**
 * [BIZ_AUTO_09] 自动化跨境合规报关单生成服务
 * @description 根据订单商品属性自动匹配 HS Code 并生成合规电子报关单，模拟对接海关 API
 */
export class CustomsDeclarationService {
  private static readonly TABLE_NAME = 'cf_customs_declarations';

  /**
   * 生成报关单 (BIZ_AUTO_09)
   */
  static async generateDeclaration(data: CustomsData): Promise<string> {
    logger.info(`[Customs] Generating declaration for Order: ${data.orderId}`);

    const declarationNumber = `DECL-${Date.now()}-${Math.floor(Math.random() * 1000)}`;

    // 1. 持久化报关单记录
    await db(this.TABLE_NAME).insert({
      tenant_id: data.tenantId,
      order_id: data.orderId,
      declaration_number: declarationNumber,
      hscode: data.hscode,
      declared_value: data.declaredValue,
      currency: data.currency,
      status: 'PENDING',
      created_at: new Date(),
      updated_at: new Date()
    });

    // 2. 模拟提交至海关系统 (BIZ_AUTO_09)
    await this.submitToCustoms(declarationNumber);

    return declarationNumber;
  }

  private static async submitToCustoms(declarationNumber: string): Promise<void> {
    logger.info(`[Customs] [API_CALL] Submitting declaration ${declarationNumber} to customs authority.`);

    // 模拟成功提交并获得释放状态
    await db(this.TABLE_NAME).where({ declaration_number: declarationNumber }).update({
      status: 'SUBMITTED',
      updated_at: new Date()
    });

    // 异步释放模拟
    setTimeout(async () => {
      await db(this.TABLE_NAME).where({ declaration_number: declarationNumber }).update({
        status: 'RELEASED',
        updated_at: new Date()
      });
      logger.info(`[Customs] Declaration ${declarationNumber} RELEASED by customs.`);
    }, 2000);
  }

  /**
   * HS Code 智能匹配逻辑 (模拟)
   */
  static async matchHSCode(productTitle: string): Promise<string> {
    if (productTitle.toLowerCase().includes('phone')) return '8517.12.00';
    if (productTitle.toLowerCase().includes('watch')) return '9102.11.00';
    return '0000.00.00'; // 默认通用
  }
}
