import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IVolumioConfig } from './volumio.types.js';
import { volumioDefaultPort } from './volumio.types.js';

const defaultTimeoutMs = 5000;

export class VolumioConfigFlow implements IConfigFlow<IVolumioConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IVolumioConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect Volumio',
      description: 'Configure the local Volumio REST API endpoint.',
      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 = this.stringValue(valuesArg.host) || candidateArg.host || '';
        const port = this.numberValue(valuesArg.port) || candidateArg.port || volumioDefaultPort;
        if (!host) {
          return { kind: 'error', title: 'Volumio setup failed', error: 'Volumio host is required.' };
        }
        return {
          kind: 'done',
          title: 'Volumio configured',
          config: {
            host,
            port,
            name: this.stringValue(valuesArg.name) || candidateArg.name,
            uniqueId: candidateArg.id,
            timeoutMs: defaultTimeoutMs,
          },
        };
      },
    };
  }

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

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