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

export class SamsungtvConfigFlow implements IConfigFlow<ISamsungtvConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<ISamsungtvConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Connect Samsung Smart TV',
      description: 'Configure the local Samsung TV websocket endpoint. Pairing prompts and encrypted PIN mode are not handled by this native port.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: 'Websocket port', type: 'number', required: false },
        { name: 'token', label: 'Existing websocket token', type: 'password', required: false },
        { name: 'name', label: 'Name', type: 'text', required: false },
        { name: 'model', label: 'Model', type: 'text', required: false },
      ],
      submit: async (valuesArg) => {
        const host = String(valuesArg.host || candidateArg.host || '').trim();
        if (!host) {
          return { kind: 'error', error: 'Samsung TV host is required.' };
        }

        const portValue = valuesArg.port ?? candidateArg.port ?? 8001;
        const port = typeof portValue === 'number' ? portValue : Number(portValue || 8001);
        return {
          kind: 'done',
          title: 'Samsung Smart TV configured',
          config: {
            host,
            port: Number.isFinite(port) ? port : 8001,
            token: typeof valuesArg.token === 'string' && valuesArg.token ? valuesArg.token : undefined,
            name: typeof valuesArg.name === 'string' && valuesArg.name ? valuesArg.name : candidateArg.name,
            model: typeof valuesArg.model === 'string' && valuesArg.model ? valuesArg.model : candidateArg.model,
            manufacturer: candidateArg.manufacturer || 'Samsung',
            macAddress: candidateArg.macAddress,
            ssdpRenderingControlLocation: typeof candidateArg.metadata?.ssdpRenderingControlLocation === 'string' ? candidateArg.metadata.ssdpRenderingControlLocation : undefined,
            ssdpMainTvAgentLocation: typeof candidateArg.metadata?.ssdpMainTvAgentLocation === 'string' ? candidateArg.metadata.ssdpMainTvAgentLocation : undefined,
          },
        };
      },
    };
  }
}
