import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IUnifiConfig } from './unifi.types.js';
import { unifiDefaultPort, unifiDefaultSite } from './unifi.types.js';

export class UnifiConfigFlow implements IConfigFlow<IUnifiConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IUnifiConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect UniFi Network',
      description: 'Provide a local UniFi Network controller host and a local controller account. Credentials are only used for setup/runtime and are never added to discovery records.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: 'Port', type: 'number', required: true },
        { name: 'site', label: 'Site', type: 'text', required: true },
        { name: 'username', label: 'Username', type: 'text', required: true },
        { name: 'password', label: 'Password', type: 'password', required: true },
        { name: 'verifySsl', label: 'Verify SSL certificate', type: 'boolean' },
      ],
      submit: async (valuesArg) => ({
        kind: 'done',
        title: 'UniFi Network configured',
        config: {
          host: String(valuesArg.host || candidateArg.host || ''),
          port: Number(valuesArg.port || candidateArg.port || unifiDefaultPort),
          site: String(valuesArg.site || candidateArg.metadata?.site || unifiDefaultSite),
          username: String(valuesArg.username || ''),
          password: String(valuesArg.password || ''),
          verifySsl: valuesArg.verifySsl === true,
          controller: {
            id: candidateArg.id,
            host: candidateArg.host,
            port: candidateArg.port || unifiDefaultPort,
            site: String(valuesArg.site || candidateArg.metadata?.site || unifiDefaultSite),
          },
        },
      }),
    };
  }
}
