import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IHeosConfig } from './heos.types.js';
import { heosDefaultPort } from './heos.types.js';

export class HeosConfigFlow implements IConfigFlow<IHeosConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IHeosConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect Denon HEOS',
      description: candidateArg.source === 'manual'
        ? 'Configure a local HEOS host.'
        : 'Confirm or adjust the discovered local HEOS host.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: 'Port', type: 'number' },
        { name: 'username', label: 'HEOS Account Username', type: 'text' },
        { name: 'password', label: 'HEOS Account Password', type: 'password' },
      ],
      submit: async (valuesArg) => {
        const host = stringValue(valuesArg.host) || candidateArg.host;
        if (!host) {
          return { kind: 'error', title: 'HEOS host required', error: 'HEOS setup requires a host.' };
        }
        const port = numberValue(valuesArg.port) || candidateArg.port || heosDefaultPort;
        return {
          kind: 'done',
          title: 'HEOS configured',
          config: {
            host,
            port,
            name: candidateArg.name,
            manufacturer: candidateArg.manufacturer,
            model: candidateArg.model,
            serialNumber: candidateArg.serialNumber,
            username: stringValue(valuesArg.username),
            password: stringValue(valuesArg.password),
          },
        };
      },
    };
  }
}

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