/**
 * POST /api/v1/auth/register/am — jeu de test officiel Fatima EL MANSOURI (docs/test-data + seed).
 * Email : fatima.elmansouri@ptits-pas.fr
 *
 * Photo attendue : tests/ressources/photos/mansouri-fatima.png
 * Données alignées sur database/seed/03_seed_test_data.sql (NIR, dates, agrément, adresse).
 *
 * Usage : node tests/scripts/register-am-mansouri-test.mjs [BASE_URL]
 */

import fs from 'fs';
import path from 'path';
import os from 'os';
import https from 'https';
import http from 'http';
import { execSync } from 'child_process';
import { fileURLToPath } from 'url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.join(__dirname, '..', '..');
const photosDir = path.join(__dirname, '..', 'ressources', 'photos');

function shrinkToJpeg(inputPath, label) {
  const out = path.join(os.tmpdir(), `ptitspas-${label}-${Date.now()}.jpg`);
  const cmd = `npx --yes sharp-cli -i ${JSON.stringify(inputPath)} -o ${JSON.stringify(out)} -mq80 resize 600 600`;
  execSync(cmd, { cwd: repoRoot, stdio: 'inherit', shell: true });
  return out;
}

function toDataUri(filePath) {
  const buf = fs.readFileSync(filePath);
  const ext = path.extname(filePath).toLowerCase();
  const mime =
    ext === '.jpg' || ext === '.jpeg' ? 'image/jpeg' : 'image/png';
  return `data:${mime};base64,${buf.toString('base64')}`;
}

const photoSrc = path.join(photosDir, 'mansouri-fatima.png');

let photoPath;
try {
  console.error('Préparation photo (sharp-cli)…');
  photoPath = shrinkToJpeg(photoSrc, 'am-mansouri');

  const body = {
    email: 'fatima.elmansouri@ptits-pas.fr',
    prenom: 'Fatima',
    nom: 'EL MANSOURI',
    telephone: '0675456789',
    adresse: '17 Boulevard Aristide Briand',
    code_postal: '95870',
    ville: 'Bezons',
    photo_base64: toDataUri(photoPath),
    photo_filename: 'fatima_elmansouri.jpg',
    consentement_photo: true,
    date_naissance: '1975-11-12',
    lieu_naissance_ville: 'Casablanca',
    lieu_naissance_pays: 'Maroc',
    nir: '275119900100102',
    numero_agrement: 'AGR-2017-095002',
    date_agrement: '2017-06-15',
    capacite_accueil: 3,
    places_disponibles: 1,
    biographie:
      "Assistante maternelle expérimentée. Née à l'étranger. Spécialité 1-3 ans. " +
      'Accueil à la journée. 1 place disponible.',
    acceptation_cgu: true,
    acceptation_privacy: true,
  };

  const json = JSON.stringify(body);
  const baseArg = process.argv[2] || 'https://app.ptits-pas.fr';
  const base = new URL(baseArg.endsWith('/') ? baseArg.slice(0, -1) : baseArg);
  const url = new URL('/api/v1/auth/register/am', `${base.protocol}//${base.host}`);

  const opts = {
    hostname: url.hostname,
    port: url.port || (url.protocol === 'https:' ? 443 : 80),
    path: url.pathname,
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
      'Content-Length': Buffer.byteLength(json, 'utf8'),
    },
  };

  const lib = url.protocol === 'https:' ? https : http;

  console.error(`POST ${url.href} (payload ~${Math.round(json.length / 1024)} Ko)`);

  const req = lib.request(opts, (res) => {
    let data = '';
    res.on('data', (c) => {
      data += c;
    });
    res.on('end', () => {
      console.log('HTTP', res.statusCode);
      try {
        const j = JSON.parse(data);
        console.log(JSON.stringify(j, null, 2));
      } catch {
        console.log(data.slice(0, 4000));
      }
    });
  });

  req.on('error', (e) => {
    console.error('Erreur réseau:', e.message);
    process.exit(1);
  });

  req.setTimeout(120000, () => {
    req.destroy();
    console.error('Timeout 120s');
    process.exit(1);
  });

  req.write(json);
  req.end();
} finally {
  try {
    if (photoPath && fs.existsSync(photoPath)) fs.unlinkSync(photoPath);
  } catch {
    /* ignore */
  }
}
