/**
 * CoreTraffic Platform Service Provider
 *
 * CoreTraffic is a core infrastructure service that provides reverse proxy functionality.
 * Unlike other platform services:
 * - It doesn't provision resources for user services
 * - It's started automatically by Onebox and cannot be stopped by users
 * - It delegates to the existing reverse proxy manager for actual operations
 */

import { BasePlatformServiceProvider } from './base.js';
import type {
  IService,
  IPlatformResource,
  IPlatformServiceConfig,
  IProvisionedResource,
  IEnvVarMapping,
  TPlatformServiceType,
  TPlatformResourceType,
} from '../../../types.js';
import { logger } from '../../../logging.js';
import type { Onebox } from '../../onebox.js';

export class CoreTrafficProvider extends BasePlatformServiceProvider {
  readonly type: TPlatformServiceType = 'coretraffic';
  readonly displayName = 'CoreTraffic Reverse Proxy';
  readonly resourceTypes: TPlatformResourceType[] = [];
  readonly isCore = true;

  constructor(oneboxRef: Onebox) {
    super(oneboxRef);
  }

  async getDefaultConfig(): Promise<IPlatformServiceConfig> {
    return {
      image: 'code.foss.global/serve.zone/coretraffic:latest',
      port: 80,
      volumes: [],
      environment: {},
    };
  }

  getEnvVarMappings(): IEnvVarMapping[] {
    return [];
  }

  async deployContainer(): Promise<string> {
    logger.info('Starting CoreTraffic via reverse proxy manager...');

    const reverseProxy = this.oneboxRef.reverseProxy;
    await reverseProxy.startHttp();

    const platformService = await this.oneboxRef.database.getPlatformServiceByType(this.type);
    if (platformService) {
      await this.oneboxRef.database.updatePlatformService(platformService.id!, {
        status: 'running',
        containerId: 'onebox-coretraffic',
      });
    }

    logger.success('CoreTraffic platform service started');
    return 'onebox-coretraffic';
  }

  async stopContainer(_containerId: string): Promise<void> {
    throw new Error('CoreTraffic is a core infrastructure service and cannot be stopped');
  }

  async healthCheck(): Promise<boolean> {
    try {
      const reverseProxy = this.oneboxRef.reverseProxy;
      const status = reverseProxy.getStatus();
      return status.http.running;
    } catch (error) {
      logger.debug(`CoreTraffic health check failed: ${error}`);
      return false;
    }
  }

  async provisionResource(_userService: IService): Promise<IProvisionedResource> {
    throw new Error('CoreTraffic does not provision resources for user services');
  }

  async deprovisionResource(_resource: IPlatformResource, _credentials: Record<string, string>): Promise<void> {
    throw new Error('CoreTraffic does not manage resources for user services');
  }
}
