import fs from 'node:fs';
import { fileURLToPath } from 'node:url';
import dotenv from 'dotenv';

dotenv.config({ path: fileURLToPath(new URL('./.env', import.meta.url)) });

const BASE = `http://localhost:${process.env.PORT || 3001}`;
const USER = process.env.ADMIN_USERNAME || 'admin';
const PASS = process.env.ADMIN_PASSWORD;

const payloads = JSON.parse(fs.readFileSync(new URL('./imports-data.json', import.meta.url)));

// 1) login
const loginRes = await fetch(`${BASE}/api/auth/login`, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ username: USER, password: PASS }),
});
if (!loginRes.ok) {
  console.error('LOGIN FAILED', loginRes.status, await loginRes.text());
  process.exit(1);
}
const { token } = await loginRes.json();
console.log('✓ logged in\n');

// 2) import each
let ok = 0;
for (const p of payloads) {
  const res = await fetch(`${BASE}/api/admin/import`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
    body: JSON.stringify(p),
  });
  const data = await res.json();
  if (res.ok) {
    ok++;
    console.log(`✓ ${p.report.id}  →  article + ${data.radar.length} radar items`);
  } else {
    console.error(`✗ ${p.report.id}  →  ${res.status}`, data);
  }
}
console.log(`\nDone: ${ok}/${payloads.length} imported`);
