import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IRainbirdConfig, TRainbirdProtocol } from './rainbird.types.js';

const defaultTimeoutMs = 20000;
const defaultDurationMinutes = 6;

export class RainbirdConfigFlow implements IConfigFlow<IRainbirdConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IRainbirdConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect Rain Bird controller',
      description: 'Configure the local Rain Bird LNK WiFi controller endpoint.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'password', label: 'Password', type: 'password', required: true },
        { name: 'protocol', label: 'Protocol', type: 'select', required: false, options: [{ label: 'Auto', value: 'auto' }, { label: 'HTTP', value: 'http' }, { label: 'HTTPS', value: 'https' }] },
        { name: 'port', label: 'Port', type: 'number', required: false },
        { name: 'defaultIrrigationDurationMinutes', label: 'Default irrigation duration', type: 'number', required: false },
      ],
      submit: async (valuesArg) => {
        const protocol = this.protocolValue(valuesArg.protocol) || this.protocolMetadata(candidateArg) || 'auto';
        return {
          kind: 'done',
          title: 'Rain Bird controller configured',
          config: {
            host: this.stringValue(valuesArg.host) || candidateArg.host || '',
            password: this.stringValue(valuesArg.password) || '',
            protocol,
            port: this.numberValue(valuesArg.port) || candidateArg.port,
            name: candidateArg.name,
            uniqueId: candidateArg.id || candidateArg.macAddress || candidateArg.serialNumber,
            macAddress: candidateArg.macAddress,
            serialNumber: candidateArg.serialNumber,
            model: candidateArg.model,
            timeoutMs: defaultTimeoutMs,
            defaultIrrigationDurationMinutes: this.numberValue(valuesArg.defaultIrrigationDurationMinutes) || defaultDurationMinutes,
          },
        };
      },
    };
  }

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

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

  private protocolValue(valueArg: unknown): TRainbirdProtocol | undefined {
    return valueArg === 'auto' || valueArg === 'http' || valueArg === 'https' ? valueArg : undefined;
  }

  private protocolMetadata(candidateArg: IDiscoveryCandidate): TRainbirdProtocol | undefined {
    const protocol = candidateArg.metadata?.protocol;
    return this.protocolValue(protocol);
  }
}
