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

/**
 * [BE-S001] 店铺管理服务
 * @description 实现商户店铺的创建、管理和监控功能
 * @taskId BE-S001
 * @version 1.0
 */
export class StoreService {
  private static generateId(prefix: string): string {
    return `${prefix}_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }

  private static generateTraceId(): string {
    return `trace_${Date.now()}_${Math.random().toString(36).substr(2, 12)}`;
  }

  /**
   * 创建店铺
   * @param tenantId 租户ID
   * @param merchantId 商户ID
   * @param shopInfo 店铺信息
   */
  static async createStore(
    tenantId: string,
    merchantId: string,
    shopInfo: {
      platform: string;
      platformShopId: string;
      name: string;
      description?: string;
    }
  ): Promise<any> {
    const traceId = this.generateTraceId();

    logger.info('[StoreService] Creating store', {
      tenantId,
      merchantId,
      platform: shopInfo.platform,
      traceId,
    });

    try {
      const storeId = this.generateId('store');

      const [store] = await db('cf_shop')
        .insert({
          id: storeId,
          tenant_id: tenantId,
          merchant_id: merchantId,
          platform: shopInfo.platform,
          platform_shop_id: shopInfo.platformShopId,
          name: shopInfo.name,
          description: shopInfo.description || '',
          status: 'ACTIVE',
          trace_id: traceId,
          created_at: new Date(),
          updated_at: new Date(),
        })
        .returning('*');

      logger.info('[StoreService] Store created successfully', {
        storeId,
        merchantId,
        traceId,
      });

      return store;
    } catch (error: any) {
      logger.error('[StoreService] Store creation failed', {
        tenantId,
        merchantId,
        traceId,
        error: error.message,
      });
      throw error;
    }
  }

  /**
   * 获取商户店铺列表
   * @param merchantId 商户ID
   */
  static async getMerchantStores(merchantId: string): Promise<any[]> {
    const traceId = this.generateTraceId();

    logger.info('[StoreService] Getting merchant stores', {
      merchantId,
      traceId,
    });

    try {
      const stores = await db('cf_shop')
        .where({ merchant_id: merchantId })
        .select('*');

      logger.info('[StoreService] Merchant stores retrieved', {
        merchantId,
        storeCount: stores.length,
        traceId,
      });

      return stores;
    } catch (error: any) {
      logger.error('[StoreService] Failed to get merchant stores', {
        merchantId,
        traceId,
        error: error.message,
      });
      throw error;
    }
  }

  /**
   * 更新店铺信息
   * @param storeId 店铺ID
   * @param updates 更新信息
   */
  static async updateStore(
    storeId: string,
    updates: {
      name?: string;
      description?: string;
      status?: 'ACTIVE' | 'INACTIVE' | 'SUSPENDED';
    }
  ): Promise<any> {
    const traceId = this.generateTraceId();

    logger.info('[StoreService] Updating store', {
      storeId,
      traceId,
    });

    try {
      const [store] = await db('cf_shop')
        .where({ id: storeId })
        .update({
          ...updates,
          updated_at: new Date(),
        })
        .returning('*');

      if (!store) {
        throw new Error('Store not found');
      }

      logger.info('[StoreService] Store updated successfully', {
        storeId,
        traceId,
      });

      return store;
    } catch (error: any) {
      logger.error('[StoreService] Store update failed', {
        storeId,
        traceId,
        error: error.message,
      });
      throw error;
    }
  }

  /**
   * 初始化店铺相关数据库表
   */
  static async initTables(): Promise<void> {
    const shopTableExists = await db.schema.hasTable('cf_shop');
    if (!shopTableExists) {
      logger.info('📦 Creating cf_shop table...');
      await db.schema.createTable('cf_shop', (table) => {
        table.string('id', 64).primary();
        table.string('tenant_id', 64).notNullable();
        table.string('merchant_id', 64).notNullable();
        table.string('platform', 50).notNullable();
        table.string('platform_shop_id', 100).notNullable();
        table.string('name', 255).notNullable();
        table.text('description');
        table.enum('status', ['ACTIVE', 'INACTIVE', 'SUSPENDED']).defaultTo('ACTIVE');
        table.string('trace_id', 64);
        table.timestamps(true, true);

        table.index(['tenant_id']);
        table.index(['merchant_id']);
        table.index(['platform', 'platform_shop_id']);
        table.index(['status']);
      });
      logger.info('✅ Table cf_shop created');
    }
  }
}
