import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IForkedDaapdConfig } from './forked_daapd.types.js';
import { forkedDaapdDefaultMaxPlaylists, forkedDaapdDefaultPort, forkedDaapdDefaultTimeoutMs } from './forked_daapd.types.js';

export class ForkedDaapdConfigFlow implements IConfigFlow<IForkedDaapdConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IForkedDaapdConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect OwnTone',
      description: candidateArg.source === 'manual'
        ? 'Configure a local OwnTone JSON API endpoint.'
        : 'Confirm or adjust the discovered local OwnTone endpoint.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: 'API port', type: 'number' },
        { name: 'password', label: 'API password', type: 'password' },
        { name: 'name', label: 'Name', type: 'text' },
      ],
      submit: async (valuesArg) => {
        const host = this.stringValue(valuesArg.host) || candidateArg.host || '';
        if (!host) {
          return { kind: 'error', title: 'OwnTone setup failed', error: 'OwnTone setup requires a host.' };
        }
        const port = this.numberValue(valuesArg.port) || candidateArg.port || forkedDaapdDefaultPort;
        if (!Number.isInteger(port) || port <= 0 || port > 65535) {
          return { kind: 'error', title: 'OwnTone setup failed', error: 'OwnTone API port must be an integer between 1 and 65535.' };
        }
        return {
          kind: 'done',
          title: 'OwnTone configured',
          config: {
            host,
            port,
            password: this.stringValue(valuesArg.password) || this.stringValue(candidateArg.metadata?.password) || '',
            name: this.stringValue(valuesArg.name) || candidateArg.name,
            uniqueId: candidateArg.id,
            timeoutMs: forkedDaapdDefaultTimeoutMs,
            maxPlaylists: forkedDaapdDefaultMaxPlaylists,
          },
        };
      },
    };
  }

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