import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IDeconzConfig } from './deconz.types.js';

export class DeconzConfigFlow implements IConfigFlow<IDeconzConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IDeconzConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect deCONZ Gateway',
      description: 'Configure the local deCONZ REST API endpoint. Leave API key empty only if setup will use a snapshot fixture.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: 'Port', type: 'number' },
        { name: 'apiKey', label: 'API key', type: 'password' },
      ],
      submit: async (valuesArg) => {
        const host = String(valuesArg.host || candidateArg.host || '');
        if (!host) {
          return {
            kind: 'error',
            title: 'deCONZ configuration incomplete',
            error: 'Host is required.',
          };
        }
        return {
          kind: 'done',
          title: 'deCONZ configured',
          config: {
            bridgeId: candidateArg.id,
            host,
            port: typeof valuesArg.port === 'number' ? valuesArg.port : candidateArg.port || 80,
            apiKey: valuesArg.apiKey ? String(valuesArg.apiKey) : undefined,
            protocol: 'http',
          },
        };
      },
    };
  }
}
