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

export class ZwaveJsConfigFlow implements IConfigFlow<IZwaveJsConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IZwaveJsConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect Z-Wave JS',
      description: 'Configure the local Z-Wave JS Server WebSocket endpoint.',
      fields: [
        { name: 'url', label: 'Server URL', type: 'text', required: true },
        { name: 'schemaVersion', label: 'API schema version', type: 'number' },
      ],
      submit: async (valuesArg) => ({
        kind: 'done',
        title: 'Z-Wave JS configured',
        config: {
          url: this.stringValue(valuesArg.url) || this.urlFromCandidate(candidateArg),
          schemaVersion: this.numberValue(valuesArg.schemaVersion),
        },
      }),
    };
  }

  private urlFromCandidate(candidateArg: IDiscoveryCandidate): string {
    if (typeof candidateArg.metadata?.url === 'string') {
      return candidateArg.metadata.url;
    }
    return candidateArg.host ? `ws://${candidateArg.host}:${candidateArg.port || 3000}` : 'ws://localhost:3000';
  }

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