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

const defaultMatterServerUrl = 'ws://localhost:5580/ws';

export class MatterConfigFlow implements IConfigFlow<IMatterConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IMatterConfig>> {
    void contextArg;
    const defaultUrl = this.urlFromCandidate(candidateArg);
    return {
      kind: 'form',
      title: 'Connect Matter',
      description: `Configure the local Matter Server WebSocket endpoint. Default: ${defaultUrl}`,
      fields: [
        { name: 'url', label: 'Matter Server URL', type: 'text', required: true },
      ],
      submit: async (valuesArg) => ({
        kind: 'done',
        title: 'Matter configured',
        config: {
          url: this.stringValue(valuesArg.url) || defaultUrl,
        },
      }),
    };
  }

  private urlFromCandidate(candidateArg: IDiscoveryCandidate): string {
    if (typeof candidateArg.metadata?.url === 'string' && candidateArg.metadata.url.trim()) {
      return candidateArg.metadata.url.trim();
    }
    if (candidateArg.host) {
      return `ws://${candidateArg.host}:${candidateArg.port || 5580}/ws`;
    }
    return defaultMatterServerUrl;
  }

  private stringValue(valueArg: unknown): string | undefined {
    return typeof valueArg === 'string' && valueArg.trim() ? valueArg.trim() : undefined;
  }
}
