import type { IConfigFlow, IConfigFlowContext, IConfigFlowStep, IDiscoveryCandidate } from '../../core/types.js';
import type { IBleboxConfig, IBleboxSnapshot } from './blebox.types.js';

const defaultHost = '192.168.0.2';
const defaultPort = 80;

export class BleboxConfigFlow implements IConfigFlow<IBleboxConfig> {
  public async start(candidateArg: IDiscoveryCandidate, contextArg: IConfigFlowContext): Promise<IConfigFlowStep<IBleboxConfig>> {
    void contextArg;
    return {
      kind: 'form',
      title: 'Set up BleBox device',
      description: 'Connect to a local BleBox device over HTTP. Username and password are only required when the device has HTTP basic authentication enabled.',
      fields: [
        { name: 'host', label: 'Host', type: 'text', required: true },
        { name: 'port', label: 'Port', type: 'number', required: true },
        { name: 'username', label: 'Username', type: 'text' },
        { name: 'password', label: 'Password', type: 'password' },
      ],
      submit: async (valuesArg) => {
        const host = String(valuesArg.host || candidateArg.host || defaultHost).trim();
        const port = Number(valuesArg.port || candidateArg.port || defaultPort);
        if (!host || host.includes('://')) {
          return { kind: 'error', title: 'Invalid BleBox host', error: 'BleBox host must be a hostname or IP address without a URL scheme.' };
        }
        if (!Number.isInteger(port) || port < 1 || port > 65535) {
          return { kind: 'error', title: 'Invalid BleBox port', error: 'BleBox port must be an integer between 1 and 65535.' };
        }

        const username = optionalString(valuesArg.username);
        const password = optionalString(valuesArg.password);
        if (Boolean(username) !== Boolean(password)) {
          return { kind: 'error', title: 'Incomplete BleBox credentials', error: 'BleBox username and password must be provided together.' };
        }

        return {
          kind: 'done',
          title: 'BleBox device configured',
          config: {
            host,
            port,
            username,
            password,
            protocol: 'http',
            snapshot: isBleboxSnapshot(candidateArg.metadata?.snapshot) ? candidateArg.metadata?.snapshot : undefined,
          },
        };
      },
    };
  }
}

const optionalString = (valueArg: unknown): string | undefined => {
  const value = String(valueArg || '').trim();
  return value || undefined;
};

const isBleboxSnapshot = (valueArg: unknown): valueArg is IBleboxSnapshot => {
  return typeof valueArg === 'object' && valueArg !== null && 'device' in valueArg;
};
