import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IApcupsdConfig } from './apcupsd.types.js';
import { apcupsdDefaultPort, apcupsdDefaultTimeoutMs } from './apcupsd.types.js';

export class ApcupsdConfigFlow implements IConfigFlow<IApcupsdConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IApcupsdConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect APC UPS Daemon',
      description: 'Configure the local APCUPSd Network Information Server endpoint.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: 'TCP port', type: 'number' },
        { name: 'name', label: 'Name', type: 'text' },
      ],
      submit: async (valuesArg) => {
        const host = this.stringValue(valuesArg.host) || candidateArg.host || '';
        if (!host) {
          return { kind: 'error', title: 'APCUPSd setup failed', error: 'APCUPSd host is required.' };
        }
        const port = this.numberValue(valuesArg.port) || candidateArg.port || apcupsdDefaultPort;
        return {
          kind: 'done',
          title: 'APCUPSd configured',
          config: {
            host,
            port,
            name: this.stringValue(valuesArg.name) || candidateArg.name,
            uniqueId: candidateArg.id || `${host}:${port}`,
            transport: 'tcp',
            timeoutMs: apcupsdDefaultTimeoutMs,
          },
        };
      },
    };
  }

  private stringValue(valueArg: unknown): string | undefined {
    return typeof valueArg === 'string' && valueArg.trim() ? valueArg.trim() : undefined;
  }

  private numberValue(valueArg: unknown): number | undefined {
    if (typeof valueArg === 'number' && Number.isFinite(valueArg) && valueArg > 0) {
      return Math.round(valueArg);
    }
    if (typeof valueArg === 'string' && valueArg.trim()) {
      const parsed = Number(valueArg);
      return Number.isFinite(parsed) && parsed > 0 ? Math.round(parsed) : undefined;
    }
    return undefined;
  }
}
