import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IAxisConfig, TAxisProtocol } from './axis.types.js';

const defaultProtocol: TAxisProtocol = 'https';
const defaultPort = 443;
const defaultTimeoutMs = 10000;

export class AxisConfigFlow implements IConfigFlow<IAxisConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IAxisConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect Axis device',
      description: 'Configure the local Axis VAPIX endpoint.',
      fields: [
        { name: 'protocol', label: 'Protocol', type: 'select', required: true, options: [{ label: 'HTTPS', value: 'https' }, { label: 'HTTP', value: 'http' }] },
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: 'Port', type: 'number', required: true },
        { name: 'username', label: 'Username', type: 'text', required: true },
        { name: 'password', label: 'Password', type: 'password', required: true },
      ],
      submit: async (valuesArg) => {
        const protocol = this.protocolValue(valuesArg.protocol) || this.protocolMetadata(candidateArg) || defaultProtocol;
        const port = this.numberValue(valuesArg.port) || candidateArg.port || (protocol === 'https' ? defaultPort : 80);
        return {
          kind: 'done',
          title: 'Axis device configured',
          config: {
            protocol,
            host: this.stringValue(valuesArg.host) || candidateArg.host || '',
            port,
            username: this.stringValue(valuesArg.username) || '',
            password: this.stringValue(valuesArg.password) || '',
            name: candidateArg.name,
            uniqueId: candidateArg.id || candidateArg.macAddress || candidateArg.serialNumber,
            model: candidateArg.model,
            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 protocolValue(valueArg: unknown): TAxisProtocol | undefined {
    return valueArg === 'http' || valueArg === 'https' ? valueArg : undefined;
  }

  private protocolMetadata(candidateArg: IDiscoveryCandidate): TAxisProtocol | undefined {
    const protocol = candidateArg.metadata?.protocol;
    return protocol === 'http' || protocol === 'https' ? protocol : undefined;
  }
}
