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

export class DenonavrConfigFlow implements IConfigFlow<IDenonavrConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IDenonavrConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect Denon AVR Network Receiver',
      description: 'Configure the local Denon/Marantz AVR HTTP endpoint.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: 'Port', type: 'number' },
        { name: 'name', label: 'Name', type: 'text' },
        { name: 'model', label: 'Model', type: 'text' },
      ],
      submit: async (valuesArg) => {
        const port = typeof valuesArg.port === 'number' ? valuesArg.port : Number(valuesArg.port || candidateArg.port || 80);
        const name = stringValue(valuesArg.name) || candidateArg.name;
        const model = stringValue(valuesArg.model) || candidateArg.model;
        return {
          kind: 'done',
          title: 'Denon AVR configured',
          config: {
            host: stringValue(valuesArg.host) || candidateArg.host || '',
            port: Number.isFinite(port) ? port : 80,
            name,
            model,
            manufacturer: candidateArg.manufacturer,
            serialNumber: candidateArg.serialNumber,
            receiverInfo: name || model || candidateArg.manufacturer || candidateArg.serialNumber ? {
              name,
              friendlyName: name,
              manufacturer: candidateArg.manufacturer,
              modelName: model,
              serialNumber: candidateArg.serialNumber,
            } : undefined,
          },
        };
      },
    };
  }
}

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