import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { ITradfriConfig } from './tradfri.types.js';
import { tradfriDefaultCoapDtlsPort } from './tradfri.types.js';

export class TradfriConfigFlow implements IConfigFlow<ITradfriConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<ITradfriConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect IKEA TRADFRI Gateway',
      description: 'Configure the local gateway. Existing identity plus PSK can be used for an external command executor; security-code pairing over CoAP/DTLS is not performed by this dependency-free port.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: 'CoAP/DTLS port', type: 'number' },
        { name: 'identity', label: 'Identity', type: 'text' },
        { name: 'securityCode', label: 'Gateway security code', type: 'password' },
        { name: 'psk', label: 'Pre-shared key', type: 'password' },
      ],
      submit: async (valuesArg) => {
        const psk = this.stringValue(valuesArg.psk) || this.stringValue(candidateArg.metadata?.psk) || this.stringValue(candidateArg.metadata?.key);
        const gatewayId = this.stringValue(candidateArg.metadata?.gatewayId) || candidateArg.id;
        return {
          kind: 'done',
          title: 'IKEA TRADFRI configured',
          config: {
            host: this.stringValue(valuesArg.host) || candidateArg.host || '',
            port: this.numberValue(valuesArg.port) || candidateArg.port || tradfriDefaultCoapDtlsPort,
            gatewayId,
            identity: this.stringValue(valuesArg.identity) || this.stringValue(candidateArg.metadata?.identity),
            securityCode: this.stringValue(valuesArg.securityCode) || this.stringValue(candidateArg.metadata?.securityCode),
            psk,
            key: psk,
            gateway: {
              id: gatewayId,
              name: candidateArg.name || 'IKEA TRADFRI Gateway',
              model: candidateArg.model || 'E1526',
            },
          },
        };
      },
    };
  }

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