/**
 * Caddy Platform Service Provider
 *
 * Caddy 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 CaddyManager 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 CaddyProvider extends BasePlatformServiceProvider {
  readonly type: TPlatformServiceType = 'caddy';
  readonly displayName = 'Caddy Reverse Proxy';
  readonly resourceTypes: TPlatformResourceType[] = []; // Caddy doesn't provision resources
  readonly isCore = true; // Core infrastructure - cannot be stopped by users

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

  getDefaultConfig(): IPlatformServiceConfig {
    return {
      image: 'caddy:2-alpine',
      port: 80,
      volumes: [],
      environment: {},
    };
  }

  getEnvVarMappings(): IEnvVarMapping[] {
    // Caddy doesn't inject any env vars into user services
    return [];
  }

  /**
   * Deploy Caddy container - delegates to CaddyManager via reverseProxy
   */
  async deployContainer(): Promise<string> {
    logger.info('Starting Caddy via reverse proxy manager...');

    // Get the reverse proxy which manages Caddy
    const reverseProxy = this.oneboxRef.reverseProxy;

    // Start reverse proxy (which starts Caddy)
    await reverseProxy.startHttp();

    // Get Caddy status to find container ID
    const status = reverseProxy.getStatus();

    // Update platform service record
    const platformService = this.oneboxRef.database.getPlatformServiceByType(this.type);
    if (platformService) {
      this.oneboxRef.database.updatePlatformService(platformService.id!, {
        status: 'running',
        containerId: 'onebox-caddy', // Service name for Swarm services
      });
    }

    logger.success('Caddy platform service started');
    return 'onebox-caddy';
  }

  /**
   * Stop Caddy container - NOT ALLOWED for core infrastructure
   */
  async stopContainer(_containerId: string): Promise<void> {
    throw new Error('Caddy is a core infrastructure service and cannot be stopped');
  }

  /**
   * Check if Caddy is healthy via the reverse proxy
   */
  async healthCheck(): Promise<boolean> {
    try {
      const reverseProxy = this.oneboxRef.reverseProxy;
      const status = reverseProxy.getStatus();
      return status.http.running;
    } catch (error) {
      logger.debug(`Caddy health check failed: ${error}`);
      return false;
    }
  }

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

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