import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IMqttConfig } from './mqtt.types.js';

export class MqttConfigFlow implements IConfigFlow<IMqttConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IMqttConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect MQTT broker',
      description: 'Configure a local MQTT 3.1.1 broker and Home Assistant-style MQTT discovery.',
      fields: [
        { name: 'host', label: 'Broker host', type: 'text', required: true },
        { name: 'port', label: 'Broker port', type: 'number' },
        { name: 'protocol', label: 'Protocol', type: 'select', options: [{ label: 'MQTT', value: 'mqtt' }, { label: 'MQTTS', value: 'mqtts' }] },
        { name: 'username', label: 'Username', type: 'text' },
        { name: 'password', label: 'Password', type: 'password' },
        { name: 'clientId', label: 'Client ID', type: 'text' },
        { name: 'discoveryPrefix', label: 'Discovery prefix', type: 'text' },
      ],
      submit: async (valuesArg) => ({
        kind: 'done',
        title: 'MQTT configured',
        config: {
          host: this.stringValue(valuesArg.host) || candidateArg.host || '',
          port: this.numberValue(valuesArg.port) || candidateArg.port || 1883,
          protocol: valuesArg.protocol === 'mqtts' ? 'mqtts' : 'mqtt',
          username: this.stringValue(valuesArg.username),
          password: this.stringValue(valuesArg.password),
          clientId: this.stringValue(valuesArg.clientId),
          discovery: true,
          discoveryPrefix: this.stringValue(valuesArg.discoveryPrefix) || 'homeassistant',
        },
      }),
    };
  }

  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 : undefined;
  }
}
