import { sendJson, serverTimestamp } from '../http.js';

export const method = 'GET';
export const path = '/v1/client';

function buildClientStep1(config) {
  const {
    authToken,
    certificateFingerprint,
    certificateSerialNumber,
    mandantId,
    serverFingerprint,
  } = config;

  return {
    authCode: null,
    authToken,
    certificateFingerprint,
    certificateSerialNumber,
    mandantId,
    mandantName: null,
    mandantDatabase: null,
    serverFingerprint,
    name: null,
    serverTimestamp: serverTimestamp(),
  };
}

function buildClientStep2(authCode, config) {
  const {
    authToken,
    certificateFingerprint,
    certificateSerialNumber,
    mandantId,
    mandantName,
    mandantDatabase,
  } = config;

  return {
    authCode,
    authToken,
    certificateFingerprint,
    certificateSerialNumber,
    mandantId,
    mandantName,
    mandantDatabase,
    serverFingerprint: null,
    name: null,
    serverTimestamp: serverTimestamp(),
  };
}

export function handle(req, res, { url, pairingStore, config }) {
  const authCode = url.searchParams.get('authCode') || '';
  const name = url.searchParams.get('name') || 'JTL-POS';

  if (authCode.length <= 4 && authCode.length > 0) {
    return sendJson(res, 200, buildClientStep1(config));
  }

  if (authCode.length === 6) {
    if (pairingStore.hasPairingCode(authCode)) {
      pairingStore.revokePairingCode(authCode);
      pairingStore.registerDevice(config.authToken, name);
      return sendJson(res, 200, buildClientStep2(authCode, config));
    }
    return sendJson(res, 400, { Message: 'Der Authentifizierungscode ist falsch.' });
  }

  return sendJson(res, 400, { Message: 'Keinen passenden Authentifizierungscode gefunden.' });
}
