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

export interface Warehouse {
  id: string;
  tenantId: string;
  name: string;
  type: 'LOCAL' | 'OVERSEAS' | 'FBA' | 'THIRD_PARTY';
  countryCode: string;
  address?: string;
  isActive: boolean;
}

/**
 * [CORE_TRADE_01] 多仓主数据管理服务
 */
export class WarehouseService {
  private static readonly TABLE_NAME = 'cf_warehouses';

  /**
   * 初始化数据库表
   */
  static async initTable() {
    const hasWarehouseTable = await db.schema.hasTable(this.TABLE_NAME);
    if (!hasWarehouseTable) {
      console.log(`📦 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('type', 32).notNullable(); // LOCAL, OVERSEAS, FBA, THIRD_PARTY
        table.string('country_code', 8);
        table.string('address', 255);
        table.boolean('is_active').defaultTo(true);
        table.timestamps(true, true);
        table.index(['tenant_id', 'type']);
      });
      console.log(`✅ Table ${this.TABLE_NAME} created`);
    }
  }

  /**
   * 创建仓库
   */
  static async createWarehouse(warehouse: Warehouse): Promise<void> {
    logger.info(`[Warehouse] Creating warehouse: ${warehouse.name} (${warehouse.type})`);
    
    await db(this.TABLE_NAME).insert({
      id: warehouse.id,
      tenant_id: warehouse.tenantId,
      name: warehouse.name,
      type: warehouse.type,
      country_code: warehouse.countryCode,
      address: warehouse.address,
      is_active: warehouse.isActive,
      created_at: new Date(),
      updated_at: new Date()
    });
  }

  /**
   * 获取租户的所有仓库
   */
  static async listByTenant(tenantId: string): Promise<Warehouse[]> {
    const records = await db(this.TABLE_NAME).where({ tenant_id: tenantId, is_active: true });
    
    return records.map(r => ({
      id: r.id,
      tenantId: r.tenant_id,
      name: r.name,
      type: r.type,
      countryCode: r.country_code,
      address: r.address,
      isActive: Boolean(r.is_active)
    }));
  }

  /**
   * 根据地理位置推荐最近的仓库 (Mock 逻辑)
   */
  static async recommendWarehouse(countryCode: string, tenantId: string): Promise<string> {
    const warehouses = await this.listByTenant(tenantId);
    
    // 优先匹配同国家的仓库
    const local = warehouses.find(w => w.countryCode === countryCode);
    if (local) return local.id;

    // 其次匹配海外仓
    const overseas = warehouses.find(w => w.type === 'OVERSEAS');
    if (overseas) return overseas.id;

    return 'DEFAULT';
  }
}
