/**
 * SmartProxy Platform Service Provider
 *
 * SmartProxy 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.ts';
import type {
  IService,
  IPlatformResource,
  IPlatformServiceConfig,
  IProvisionedResource,
  IEnvVarMapping,
  TPlatformServiceType,
  TPlatformResourceType,
} from '../../../types.ts';
import { logger } from '../../../logging.ts';
import type { Onebox } from '../../onebox.ts';

export class SmartProxyProvider extends BasePlatformServiceProvider {
  readonly type: TPlatformServiceType = 'smartproxy';
  readonly displayName = 'SmartProxy Reverse Proxy';
  readonly resourceTypes: TPlatformResourceType[] = [];
  readonly isCore = true;

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

  getDefaultConfig(): IPlatformServiceConfig {
    return {
      image: 'code.foss.global/host.today/ht-docker-smartproxy:latest',
      port: 80,
      volumes: [],
      environment: {},
    };
  }

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

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

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

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

    logger.success('SmartProxy platform service started');
    return 'onebox-smartproxy';
  }

  async stopContainer(_containerId: string): Promise<void> {
    throw new Error('SmartProxy 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(`SmartProxy health check failed: ${error}`);
      return false;
    }
  }

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

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