import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { ISoundtouchConfig } from './soundtouch.types.js';
import { soundtouchDefaultDlnaPort, soundtouchDefaultPort } from './soundtouch.types.js';

export class SoundtouchConfigFlow implements IConfigFlow<ISoundtouchConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<ISoundtouchConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect Bose SoundTouch',
      description: candidateArg.source === 'manual'
        ? 'Configure a local Bose SoundTouch speaker.'
        : 'Confirm or adjust the discovered local Bose SoundTouch speaker.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: 'Port', type: 'number' },
        { name: 'name', label: 'Name', type: 'text' },
      ],
      submit: async (valuesArg) => {
        const host = stringValue(valuesArg.host) || candidateArg.host;
        if (!host) {
          return { kind: 'error', title: 'SoundTouch host required', error: 'SoundTouch setup requires a host.' };
        }
        return {
          kind: 'done',
          title: 'Bose SoundTouch configured',
          config: {
            host,
            port: numberValue(valuesArg.port) || candidateArg.port || soundtouchDefaultPort,
            dlnaPort: soundtouchDefaultDlnaPort,
            name: stringValue(valuesArg.name) || candidateArg.name,
            deviceId: candidateArg.id,
            model: candidateArg.model,
            macAddress: candidateArg.macAddress,
          },
        };
      },
    };
  }
}

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

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