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

export type Platform = 'AMAZON' | 'EBAY' | 'SHOPIFY' | 'WOOCOMMERCE' | 'ALIBABA' | 'LAZADA' | 'SHOPEE' | 'CUSTOM';

export type CollectionStatus = 'PENDING' | 'COLLECTING' | 'COMPLETED' | 'FAILED';

export type FunnelStage = 
  | 'CREATED'
  | 'CONFIRMED'
  | 'PAID'
  | 'PROCESSING'
  | 'SHIPPED'
  | 'DELIVERED'
  | 'COMPLETED'
  | 'CANCELLED';

export interface OrderCentralContext {
  tenantId: string;
  shopId: string;
  taskId: string;
  traceId: string;
  businessType: 'TOC' | 'TOB';
}

export interface PlatformConfig {
  platform: Platform;
  shopId: string;
  shopName: string;
  credentials: Record<string, any>;
  syncEnabled: boolean;
  syncInterval: number;
  lastSyncAt?: Date;
}

export interface OrderCollection {
  id: string;
  tenantId: string;
  platform: Platform;
  shopId: string;
  status: CollectionStatus;
  totalOrders: number;
  collectedOrders: number;
  failedOrders: number;
  startTime: Date;
  endTime?: Date;
  errorMessage?: string;
  traceId: string;
  createdAt: Date;
}

export interface CentralizedOrder {
  id: string;
  tenantId: string;
  platform: Platform;
  platformOrderId: string;
  shopId: string;
  shopName: string;
  customerId: string;
  customerName: string;
  customerEmail?: string;
  items: OrderItem[];
  totalAmount: number;
  currency: string;
  status: string;
  funnelStage: FunnelStage;
  paymentStatus: 'PENDING' | 'PAID' | 'REFUNDED' | 'FAILED';
  shippingStatus: 'PENDING' | 'PROCESSING' | 'SHIPPED' | 'DELIVERED';
  shippingAddress: ShippingAddress;
  orderDate: Date;
  paidAt?: Date;
  shippedAt?: Date;
  deliveredAt?: Date;
  tags: string[];
  notes?: string;
  traceId: string;
  createdAt: Date;
  updatedAt: Date;
}

export interface OrderItem {
  skuId: string;
  productId: string;
  productName: string;
  quantity: number;
  unitPrice: number;
  totalPrice: number;
  imageUrl?: string;
}

export interface ShippingAddress {
  name: string;
  phone?: string;
  address1: string;
  address2?: string;
  city: string;
  state?: string;
  postalCode: string;
  country: string;
}

export interface OrderFunnel {
  stage: FunnelStage;
  count: number;
  amount: number;
  conversionRate: number;
  dropOffRate: number;
}

export interface OrderFunnelAnalysis {
  tenantId: string;
  period: { start: Date; end: Date };
  platforms: Platform[];
  funnels: OrderFunnel[];
  totalOrders: number;
  totalAmount: number;
  averageOrderValue: number;
  conversionMetrics: {
    createdToPaid: number;
    paidToShipped: number;
    shippedToDelivered: number;
    overallCompletion: number;
  };
}

export interface PlatformOrderStats {
  platform: Platform;
  totalOrders: number;
  totalAmount: number;
  averageOrderValue: number;
  orderCountByStatus: Record<string, number>;
  topProducts: Array<{ productId: string; productName: string; count: number }>;
}

export class OrderCentralService {
  private static readonly COLLECTION_TABLE = 'cf_order_collections';
  private static readonly CENTRAL_ORDER_TABLE = 'cf_central_orders';
  private static readonly PLATFORM_CONFIG_TABLE = 'cf_platform_configs';

  static async initTables(): Promise<void> {
    await this.initCollectionTable();
    await this.initCentralOrderTable();
    await this.initPlatformConfigTable();
  }

  private static async initCollectionTable(): Promise<void> {
    const hasTable = await db.schema.hasTable(this.COLLECTION_TABLE);
    if (!hasTable) {
      logger.info(`[OrderCentral] Creating ${this.COLLECTION_TABLE} table...`);
      await db.schema.createTable(this.COLLECTION_TABLE, (table) => {
        table.string('id', 64).primary();
        table.string('tenant_id', 64).notNullable();
        table.enum('platform', ['AMAZON', 'EBAY', 'SHOPIFY', 'WOOCOMMERCE', 'ALIBABA', 'LAZADA', 'SHOPEE', 'CUSTOM']).notNullable();
        table.string('shop_id', 64).notNullable();
        table.enum('status', ['PENDING', 'COLLECTING', 'COMPLETED', 'FAILED']).defaultTo('PENDING');
        table.integer('total_orders').defaultTo(0);
        table.integer('collected_orders').defaultTo(0);
        table.integer('failed_orders').defaultTo(0);
        table.datetime('start_time');
        table.datetime('end_time');
        table.text('error_message');
        table.string('trace_id', 64);
        table.timestamps(true, true);

        table.index(['tenant_id', 'platform'], 'idx_collection_tenant_platform');
        table.index(['tenant_id', 'status'], 'idx_collection_tenant_status');
      });
      logger.info(`[OrderCentral] Table ${this.COLLECTION_TABLE} created`);
    }
  }

  private static async initCentralOrderTable(): Promise<void> {
    const hasTable = await db.schema.hasTable(this.CENTRAL_ORDER_TABLE);
    if (!hasTable) {
      logger.info(`[OrderCentral] Creating ${this.CENTRAL_ORDER_TABLE} table...`);
      await db.schema.createTable(this.CENTRAL_ORDER_TABLE, (table) => {
        table.string('id', 64).primary();
        table.string('tenant_id', 64).notNullable();
        table.enum('platform', ['AMAZON', 'EBAY', 'SHOPIFY', 'WOOCOMMERCE', 'ALIBABA', 'LAZADA', 'SHOPEE', 'CUSTOM']).notNullable();
        table.string('platform_order_id', 128).notNullable();
        table.string('shop_id', 64).notNullable();
        table.string('shop_name', 128);
        table.string('customer_id', 64).notNullable();
        table.string('customer_name', 128);
        table.string('customer_email', 128);
        table.json('items');
        table.decimal('total_amount', 15, 2);
        table.string('currency', 10).defaultTo('USD');
        table.string('status', 32);
        table.enum('funnel_stage', ['CREATED', 'CONFIRMED', 'PAID', 'PROCESSING', 'SHIPPED', 'DELIVERED', 'COMPLETED', 'CANCELLED']).defaultTo('CREATED');
        table.enum('payment_status', ['PENDING', 'PAID', 'REFUNDED', 'FAILED']).defaultTo('PENDING');
        table.enum('shipping_status', ['PENDING', 'PROCESSING', 'SHIPPED', 'DELIVERED']).defaultTo('PENDING');
        table.json('shipping_address');
        table.datetime('order_date');
        table.datetime('paid_at');
        table.datetime('shipped_at');
        table.datetime('delivered_at');
        table.json('tags');
        table.text('notes');
        table.string('trace_id', 64);
        table.timestamps(true, true);

        table.unique(['tenant_id', 'platform', 'platform_order_id'], 'idx_central_order_unique');
        table.index(['tenant_id', 'platform'], 'idx_central_order_tenant_platform');
        table.index(['tenant_id', 'funnel_stage'], 'idx_central_order_tenant_stage');
        table.index(['tenant_id', 'order_date'], 'idx_central_order_tenant_date');
      });
      logger.info(`[OrderCentral] Table ${this.CENTRAL_ORDER_TABLE} created`);
    }
  }

  private static async initPlatformConfigTable(): Promise<void> {
    const hasTable = await db.schema.hasTable(this.PLATFORM_CONFIG_TABLE);
    if (!hasTable) {
      logger.info(`[OrderCentral] Creating ${this.PLATFORM_CONFIG_TABLE} table...`);
      await db.schema.createTable(this.PLATFORM_CONFIG_TABLE, (table) => {
        table.string('id', 64).primary();
        table.string('tenant_id', 64).notNullable();
        table.enum('platform', ['AMAZON', 'EBAY', 'SHOPIFY', 'WOOCOMMERCE', 'ALIBABA', 'LAZADA', 'SHOPEE', 'CUSTOM']).notNullable();
        table.string('shop_id', 64).notNullable();
        table.string('shop_name', 128);
        table.json('credentials');
        table.boolean('sync_enabled').defaultTo(true);
        table.integer('sync_interval').defaultTo(30);
        table.datetime('last_sync_at');
        table.timestamps(true, true);

        table.unique(['tenant_id', 'platform', 'shop_id'], 'idx_platform_config_unique');
      });
      logger.info(`[OrderCentral] Table ${this.PLATFORM_CONFIG_TABLE} created`);
    }
  }

  static async registerPlatform(
    context: OrderCentralContext,
    config: Omit<PlatformConfig, 'lastSyncAt'>
  ): Promise<{ success: boolean; configId: string }> {
    const { tenantId, traceId } = context;
    logger.info(`[OrderCentral] Registering platform: ${config.platform} - ${config.shopName}`);

    const configId = this.generateConfigId();

    await db(this.PLATFORM_CONFIG_TABLE).insert({
      id: configId,
      tenant_id: tenantId,
      platform: config.platform,
      shop_id: config.shopId,
      shop_name: config.shopName,
      credentials: JSON.stringify(config.credentials),
      sync_enabled: config.syncEnabled,
      sync_interval: config.syncInterval,
      trace_id: traceId,
      created_at: new Date(),
      updated_at: new Date()
    });

    return { success: true, configId };
  }

  static async collectOrders(
    context: OrderCentralContext,
    params: {
      platform: Platform;
      shopId: string;
      startDate?: Date;
      endDate?: Date;
    }
  ): Promise<{ success: boolean; collectionId: string; status: CollectionStatus }> {
    const { tenantId, traceId } = context;
    const { platform, shopId, startDate, endDate } = params;

    logger.info(`[OrderCentral] Starting collection - platform: ${platform}, shopId: ${shopId}`);

    const collectionId = this.generateCollectionId();

    await db(this.COLLECTION_TABLE).insert({
      id: collectionId,
      tenant_id: tenantId,
      platform,
      shop_id: shopId,
      status: 'COLLECTING',
      total_orders: 0,
      collected_orders: 0,
      failed_orders: 0,
      start_time: new Date(),
      trace_id: traceId,
      created_at: new Date(),
      updated_at: new Date()
    });

    try {
      const platformConfig = await db(this.PLATFORM_CONFIG_TABLE)
        .where({ tenant_id: tenantId, platform, shop_id: shopId })
        .first();

      if (!platformConfig) {
        throw new Error(`Platform config not found for ${platform}/${shopId}`);
      }

      const orders = await this.fetchOrdersFromPlatform(
        platform,
        platformConfig.credentials,
        startDate,
        endDate
      );

      await db(this.COLLECTION_TABLE)
        .where({ id: collectionId })
        .update({ total_orders: orders.length });

      let collected = 0;
      let failed = 0;

      for (const order of orders) {
        try {
          await this.saveCentralizedOrder(tenantId, platform, shopId, platformConfig.shop_name, order, traceId);
          collected++;
        } catch (error: any) {
          logger.error(`[OrderCentral] Failed to save order ${order.id}: ${error.message}`);
          failed++;
        }
      }

      await db(this.COLLECTION_TABLE)
        .where({ id: collectionId })
        .update({
          status: 'COMPLETED',
          collected_orders: collected,
          failed_orders: failed,
          end_time: new Date(),
          updated_at: new Date()
        });

      await db(this.PLATFORM_CONFIG_TABLE)
        .where({ tenant_id: tenantId, platform, shop_id: shopId })
        .update({ last_sync_at: new Date(), updated_at: new Date() });

      DomainEventBus.publish('order_collection.completed', {
        collectionId,
        tenantId,
        platform,
        shopId,
        collected,
        failed,
        timestamp: new Date()
      });

      return { success: true, collectionId, status: 'COMPLETED' };
    } catch (error: any) {
      await db(this.COLLECTION_TABLE)
        .where({ id: collectionId })
        .update({
          status: 'FAILED',
          error_message: error.message,
          end_time: new Date(),
          updated_at: new Date()
        });

      return { success: false, collectionId, status: 'FAILED' };
    }
  }

  private static async fetchOrdersFromPlatform(
    platform: Platform,
    credentials: any,
    startDate?: Date,
    endDate?: Date
  ): Promise<any[]> {
    logger.info(`[OrderCentral] Fetching orders from ${platform}`);

    return [];
  }

  private static async saveCentralizedOrder(
    tenantId: string,
    platform: Platform,
    shopId: string,
    shopName: string,
    orderData: any,
    traceId: string
  ): Promise<void> {
    const centralOrder: Partial<CentralizedOrder> = {
      id: this.generateOrderId(),
      tenantId,
      platform,
      platformOrderId: orderData.id || orderData.orderId,
      shopId,
      shopName,
      customerId: orderData.customerId || 'unknown',
      customerName: orderData.customerName || orderData.buyerName || 'Unknown',
      customerEmail: orderData.customerEmail || orderData.buyerEmail,
      items: orderData.items || [],
      totalAmount: orderData.totalAmount || 0,
      currency: orderData.currency || 'USD',
      status: orderData.status || 'PENDING',
      funnelStage: this.mapToFunnelStage(orderData.status),
      paymentStatus: orderData.paymentStatus || 'PENDING',
      shippingStatus: orderData.shippingStatus || 'PENDING',
      shippingAddress: orderData.shippingAddress || {},
      orderDate: orderData.orderDate || orderData.createdAt || new Date(),
      paidAt: orderData.paidAt,
      shippedAt: orderData.shippedAt,
      deliveredAt: orderData.deliveredAt,
      tags: orderData.tags || [],
      notes: orderData.notes,
      traceId,
      createdAt: new Date(),
      updatedAt: new Date()
    };

    await db(this.CENTRAL_ORDER_TABLE)
      .insert({
        id: centralOrder.id,
        tenant_id: centralOrder.tenantId,
        platform: centralOrder.platform,
        platform_order_id: centralOrder.platformOrderId,
        shop_id: centralOrder.shopId,
        shop_name: centralOrder.shopName,
        customer_id: centralOrder.customerId,
        customer_name: centralOrder.customerName,
        customer_email: centralOrder.customerEmail,
        items: JSON.stringify(centralOrder.items),
        total_amount: centralOrder.totalAmount,
        currency: centralOrder.currency,
        status: centralOrder.status,
        funnel_stage: centralOrder.funnelStage,
        payment_status: centralOrder.paymentStatus,
        shipping_status: centralOrder.shippingStatus,
        shipping_address: JSON.stringify(centralOrder.shippingAddress),
        order_date: centralOrder.orderDate,
        paid_at: centralOrder.paidAt,
        shipped_at: centralOrder.shippedAt,
        delivered_at: centralOrder.deliveredAt,
        tags: JSON.stringify(centralOrder.tags),
        notes: centralOrder.notes,
        trace_id: centralOrder.traceId,
        created_at: centralOrder.createdAt,
        updated_at: centralOrder.updatedAt
      })
      .onConflict(['tenant_id', 'platform', 'platform_order_id'])
      .merge();
  }

  private static mapToFunnelStage(status: string): FunnelStage {
    const statusMap: Record<string, FunnelStage> = {
      'PENDING': 'CREATED',
      'CREATED': 'CREATED',
      'CONFIRMED': 'CONFIRMED',
      'PAID': 'PAID',
      'PROCESSING': 'PROCESSING',
      'SHIPPED': 'SHIPPED',
      'DELIVERED': 'DELIVERED',
      'COMPLETED': 'COMPLETED',
      'CANCELLED': 'CANCELLED',
      'REFUNDED': 'CANCELLED'
    };

    return statusMap[status?.toUpperCase()] || 'CREATED';
  }

  static async getCentralizedOrders(
    tenantId: string,
    params: {
      platforms?: Platform[];
      shopIds?: string[];
      funnelStage?: FunnelStage;
      status?: string;
      startDate?: Date;
      endDate?: Date;
      search?: string;
      page?: number;
      pageSize?: number;
    }
  ): Promise<{ orders: CentralizedOrder[]; total: number }> {
    const { platforms, shopIds, funnelStage, status, startDate, endDate, search, page = 1, pageSize = 20 } = params;
    const offset = (page - 1) * pageSize;

    let query = db(this.CENTRAL_ORDER_TABLE).where({ tenant_id: tenantId });

    if (platforms && platforms.length > 0) {
      query = query.whereIn('platform', platforms);
    }
    if (shopIds && shopIds.length > 0) {
      query = query.whereIn('shop_id', shopIds);
    }
    if (funnelStage) {
      query = query.where({ funnel_stage: funnelStage });
    }
    if (status) {
      query = query.where({ status });
    }
    if (startDate) {
      query = query.where('order_date', '>=', startDate);
    }
    if (endDate) {
      query = query.where('order_date', '<=', endDate);
    }
    if (search) {
      query = query.where(function(this: any) {
        this.where('platform_order_id', 'like', `%${search}%`)
          .orWhere('customer_name', 'like', `%${search}%`)
          .orWhere('customer_email', 'like', `%${search}%`);
      });
    }

    const total = await query.clone().count('id as count').first();

    const orders = await query
      .offset(offset)
      .limit(pageSize)
      .orderBy('order_date', 'desc');

    return {
      orders: orders.map(o => this.mapToCentralizedOrder(o)),
      total: Number(total?.count || 0)
    };
  }

  static async getFunnelAnalysis(
    tenantId: string,
    params: {
      platforms?: Platform[];
      startDate?: Date;
      endDate?: Date;
    }
  ): Promise<OrderFunnelAnalysis> {
    const { platforms, startDate, endDate } = params;

    let query = db(this.CENTRAL_ORDER_TABLE).where({ tenant_id: tenantId });

    if (platforms && platforms.length > 0) {
      query = query.whereIn('platform', platforms);
    }
    if (startDate) {
      query = query.where('order_date', '>=', startDate);
    }
    if (endDate) {
      query = query.where('order_date', '<=', endDate);
    }

    const orders = await query.select('funnel_stage', 'total_amount');

    const stageData: Record<FunnelStage, { count: number; amount: number }> = {
      'CREATED': { count: 0, amount: 0 },
      'CONFIRMED': { count: 0, amount: 0 },
      'PAID': { count: 0, amount: 0 },
      'PROCESSING': { count: 0, amount: 0 },
      'SHIPPED': { count: 0, amount: 0 },
      'DELIVERED': { count: 0, amount: 0 },
      'COMPLETED': { count: 0, amount: 0 },
      'CANCELLED': { count: 0, amount: 0 }
    };

    let totalAmount = 0;
    orders.forEach(order => {
      const stage = order.funnel_stage as FunnelStage;
      if (stageData[stage]) {
        stageData[stage].count++;
        stageData[stage].amount += Number(order.total_amount);
      }
      totalAmount += Number(order.total_amount);
    });

    const totalOrders = orders.length;
    const stages: FunnelStage[] = ['CREATED', 'CONFIRMED', 'PAID', 'PROCESSING', 'SHIPPED', 'DELIVERED', 'COMPLETED'];

    const funnels: OrderFunnel[] = stages.map((stage, index) => {
      const prevCount = index > 0 ? stageData[stages[index - 1]].count : totalOrders;
      const count = stageData[stage].count;
      const conversionRate = totalOrders > 0 ? (count / totalOrders) * 100 : 0;
      const dropOffRate = prevCount > 0 ? ((prevCount - count) / prevCount) * 100 : 0;

      return {
        stage,
        count,
        amount: stageData[stage].amount,
        conversionRate: Math.round(conversionRate * 100) / 100,
        dropOffRate: Math.round(dropOffRate * 100) / 100
      };
    });

    const createdCount = stageData['CREATED'].count;
    const paidCount = stageData['PAID'].count;
    const shippedCount = stageData['SHIPPED'].count;
    const deliveredCount = stageData['DELIVERED'].count;
    const completedCount = stageData['COMPLETED'].count;

    return {
      tenantId,
      period: {
        start: startDate || new Date(0),
        end: endDate || new Date()
      },
      platforms: platforms || [],
      funnels,
      totalOrders,
      totalAmount,
      averageOrderValue: totalOrders > 0 ? totalAmount / totalOrders : 0,
      conversionMetrics: {
        createdToPaid: createdCount > 0 ? (paidCount / createdCount) * 100 : 0,
        paidToShipped: paidCount > 0 ? (shippedCount / paidCount) * 100 : 0,
        shippedToDelivered: shippedCount > 0 ? (deliveredCount / shippedCount) * 100 : 0,
        overallCompletion: totalOrders > 0 ? (completedCount / totalOrders) * 100 : 0
      }
    };
  }

  static async getPlatformStats(
    tenantId: string,
    params: {
      platforms?: Platform[];
      startDate?: Date;
      endDate?: Date;
    }
  ): Promise<PlatformOrderStats[]> {
    const { platforms, startDate, endDate } = params;

    let query = db(this.CENTRAL_ORDER_TABLE).where({ tenant_id: tenantId });

    if (platforms && platforms.length > 0) {
      query = query.whereIn('platform', platforms);
    }
    if (startDate) {
      query = query.where('order_date', '>=', startDate);
    }
    if (endDate) {
      query = query.where('order_date', '<=', endDate);
    }

    const orders = await query.select('platform', 'status', 'total_amount', 'items');

    const platformStats: Record<Platform, PlatformOrderStats> = {} as Record<Platform, PlatformOrderStats>;

    orders.forEach(order => {
      const platform = order.platform as Platform;
      if (!platformStats[platform]) {
        platformStats[platform] = {
          platform,
          totalOrders: 0,
          totalAmount: 0,
          averageOrderValue: 0,
          orderCountByStatus: {},
          topProducts: []
        };
      }

      platformStats[platform].totalOrders++;
      platformStats[platform].totalAmount += Number(order.total_amount);
      platformStats[platform].orderCountByStatus[order.status] = 
        (platformStats[platform].orderCountByStatus[order.status] || 0) + 1;
    });

    Object.values(platformStats).forEach(stats => {
      stats.averageOrderValue = stats.totalOrders > 0 ? stats.totalAmount / stats.totalOrders : 0;
    });

    return Object.values(platformStats);
  }

  static async getCollectionHistory(
    tenantId: string,
    params: {
      platform?: Platform;
      status?: CollectionStatus;
      page?: number;
      pageSize?: number;
    }
  ): Promise<{ collections: OrderCollection[]; total: number }> {
    const { platform, status, page = 1, pageSize = 20 } = params;
    const offset = (page - 1) * pageSize;

    let query = db(this.COLLECTION_TABLE).where({ tenant_id: tenantId });

    if (platform) {
      query = query.where({ platform });
    }
    if (status) {
      query = query.where({ status });
    }

    const total = await query.clone().count('id as count').first();

    const collections = await query
      .offset(offset)
      .limit(pageSize)
      .orderBy('created_at', 'desc');

    return {
      collections: collections.map(c => this.mapToCollection(c)),
      total: Number(total?.count || 0)
    };
  }

  private static mapToCentralizedOrder(row: any): CentralizedOrder {
    return {
      id: row.id,
      tenantId: row.tenant_id,
      platform: row.platform,
      platformOrderId: row.platform_order_id,
      shopId: row.shop_id,
      shopName: row.shop_name,
      customerId: row.customer_id,
      customerName: row.customer_name,
      customerEmail: row.customer_email,
      items: typeof row.items === 'string' ? JSON.parse(row.items) : row.items,
      totalAmount: Number(row.total_amount),
      currency: row.currency,
      status: row.status,
      funnelStage: row.funnel_stage,
      paymentStatus: row.payment_status,
      shippingStatus: row.shipping_status,
      shippingAddress: typeof row.shipping_address === 'string' ? JSON.parse(row.shipping_address) : row.shipping_address,
      orderDate: row.order_date,
      paidAt: row.paid_at,
      shippedAt: row.shipped_at,
      deliveredAt: row.delivered_at,
      tags: typeof row.tags === 'string' ? JSON.parse(row.tags) : row.tags,
      notes: row.notes,
      traceId: row.trace_id,
      createdAt: row.created_at,
      updatedAt: row.updated_at
    };
  }

  private static mapToCollection(row: any): OrderCollection {
    return {
      id: row.id,
      tenantId: row.tenant_id,
      platform: row.platform,
      shopId: row.shop_id,
      status: row.status,
      totalOrders: row.total_orders,
      collectedOrders: row.collected_orders,
      failedOrders: row.failed_orders,
      startTime: row.start_time,
      endTime: row.end_time,
      errorMessage: row.error_message,
      traceId: row.trace_id,
      createdAt: row.created_at
    };
  }

  private static generateCollectionId(): string {
    return `COL-${Date.now()}-${Math.random().toString(36).substr(2, 6).toUpperCase()}`;
  }

  private static generateOrderId(): string {
    return `CO-${Date.now()}-${Math.random().toString(36).substr(2, 6).toUpperCase()}`;
  }

  private static generateConfigId(): string {
    return `PC-${Date.now()}-${Math.random().toString(36).substr(2, 6).toUpperCase()}`;
  }
}
