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

export class ShellyConfigFlow implements IConfigFlow<IShellyConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IShellyConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect Shelly',
      description: 'Configure the local Shelly HTTP endpoint. Password is only needed when device authentication is enabled.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: 'Port', type: 'number' },
        { name: 'protocol', label: 'Protocol', type: 'select', options: [
          { label: 'HTTP', value: 'http' },
          { label: 'HTTPS', value: 'https' },
        ] },
        { name: 'username', label: 'Username', type: 'text' },
        { name: 'password', label: 'Password', type: 'password' },
      ],
      submit: async (valuesArg) => ({
        kind: 'done',
        title: 'Shelly configured',
        config: {
          host: String(valuesArg.host || candidateArg.host || ''),
          port: typeof valuesArg.port === 'number' ? valuesArg.port : candidateArg.port || 80,
          protocol: valuesArg.protocol === 'https' ? 'https' : 'http',
          username: String(valuesArg.username || 'admin'),
          password: valuesArg.password ? String(valuesArg.password) : undefined,
        },
      }),
    };
  }
}
