#!/usr/bin/env node
/**
 * Cree un token API static pour l'admin Directus et le set dans le user.
 * Puis affiche le token (a coller dans .env DIRECTUS_TOKEN=...)
 *
 * Usage : node scripts/create-admin-token.mjs
 */
import { randomBytes } from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';

const URL_BASE = process.env.DIRECTUS_PUBLIC_URL || 'http://localhost:8055';
const EMAIL = process.env.DIRECTUS_ADMIN_EMAIL || 'corentin.jog@gmail.com';
const PASSWORD = process.env.DIRECTUS_ADMIN_PASSWORD || 'changeme-please';

async function api(method, path, body, token) {
  const headers = { 'Content-Type': 'application/json' };
  if (token) headers.Authorization = `Bearer ${token}`;
  const res = await fetch(`${URL_BASE}${path}`, {
    method,
    headers,
    body: body ? JSON.stringify(body) : undefined,
  });
  const text = await res.text();
  let json;
  try { json = text ? JSON.parse(text) : null; } catch { json = text; }
  if (!res.ok) throw new Error(`${method} ${path} → ${res.status}\n${JSON.stringify(json, null, 2)}`);
  return json;
}

(async () => {
  const login = await api('POST', '/auth/login', { email: EMAIL, password: PASSWORD });
  const authToken = login.data.access_token;

  const me = await api('GET', '/users/me?fields=id,email,token', null, authToken);
  const userId = me.data.id;

  let token = me.data.token;
  if (!token) {
    token = randomBytes(24).toString('hex');
    await api('PATCH', `/users/${userId}`, { token }, authToken);
    console.log('✓ Admin static token created and assigned');
  } else {
    console.log('= Admin already has a static token, reusing it');
  }

  // Update .env file in place if it exists
  const envPath = path.resolve(process.cwd(), '.env');
  if (fs.existsSync(envPath)) {
    let env = fs.readFileSync(envPath, 'utf8');
    if (/^DIRECTUS_TOKEN=.*/m.test(env)) {
      env = env.replace(/^DIRECTUS_TOKEN=.*/m, `DIRECTUS_TOKEN=${token}`);
    } else {
      env += `\nDIRECTUS_TOKEN=${token}\n`;
    }
    fs.writeFileSync(envPath, env);
    console.log(`✓ .env updated with DIRECTUS_TOKEN`);
  }

  console.log('\nToken value :');
  console.log(token);
  console.log('\nNow restart Astro dev to pick the new env.');
})().catch((e) => {
  console.error('FAILED:', e.message);
  process.exit(1);
});
