import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IPlexConfig } from './plex.types.js';
import { plexDefaultPort } from './plex.types.js';

const defaultTimeoutMs = 7000;

export class PlexConfigFlow implements IConfigFlow<IPlexConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IPlexConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect Plex Media Server',
      description: 'Configure a local Plex Media Server HTTP API endpoint. A token is required for sessions, libraries, and controls on claimed servers.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: 'Port', type: 'number' },
        { name: 'ssl', label: 'Use HTTPS', type: 'boolean' },
        { name: 'verifySsl', label: 'Verify SSL certificates', type: 'boolean' },
        { name: 'token', label: 'Plex token', type: 'password' },
        { name: 'name', label: 'Name', type: 'text' },
      ],
      submit: async (valuesArg) => {
        const host = this.stringValue(valuesArg.host) || candidateArg.host || this.stringMetadata(candidateArg, 'host') || '';
        const port = this.numberValue(valuesArg.port) || candidateArg.port || plexDefaultPort;
        const ssl = this.booleanValue(valuesArg.ssl) ?? this.booleanMetadata(candidateArg, 'ssl') ?? false;
        return {
          kind: 'done',
          title: 'Plex configured',
          config: {
            host,
            port,
            ssl,
            verifySsl: this.booleanValue(valuesArg.verifySsl) ?? this.booleanMetadata(candidateArg, 'verifySsl') ?? true,
            token: this.stringValue(valuesArg.token),
            name: this.stringValue(valuesArg.name) || candidateArg.name,
            serverIdentifier: candidateArg.id,
            url: host ? `${ssl ? 'https' : 'http'}://${host}:${port}` : undefined,
            timeoutMs: defaultTimeoutMs,
          },
        };
      },
    };
  }

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

  private numberValue(valueArg: unknown): number | undefined {
    return typeof valueArg === 'number' && Number.isFinite(valueArg) ? valueArg : undefined;
  }

  private booleanValue(valueArg: unknown): boolean | undefined {
    return typeof valueArg === 'boolean' ? valueArg : undefined;
  }

  private stringMetadata(candidateArg: IDiscoveryCandidate, keyArg: string): string | undefined {
    const value = candidateArg.metadata?.[keyArg];
    return typeof value === 'string' && value.trim() ? value.trim() : undefined;
  }

  private booleanMetadata(candidateArg: IDiscoveryCandidate, keyArg: string): boolean | undefined {
    const value = candidateArg.metadata?.[keyArg];
    return typeof value === 'boolean' ? value : undefined;
  }
}
