#!/usr/bin/env npx tsx
/**
 * Admin script: create a 14-day trial licence in Supabase.
 *
 * Usage:
 *   npx tsx scripts/create-trial.ts <email> [quota]
 *
 * Creates a trial licence with:
 *   - plan = "trial"
 *   - quota_month = 5 generations by default (configurable)
 *   - active = true (manually deactivate after 14 days via Supabase dashboard)
 *
 * Example:
 *   npx tsx scripts/create-trial.ts prospect@charpentier.fr
 *   npx tsx scripts/create-trial.ts lead@agence.fr 10
 */

import { createClient } from '@supabase/supabase-js';
import { createHash, randomBytes } from 'crypto';
import { config } from 'dotenv';

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

const SUPABASE_URL              = process.env.SUPABASE_URL ?? '';
const SUPABASE_SERVICE_ROLE_KEY = process.env.SUPABASE_SERVICE_ROLE_KEY ?? '';

if (!SUPABASE_URL || !SUPABASE_SERVICE_ROLE_KEY) {
  console.error('Missing SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY in .env');
  process.exit(1);
}

const [, , email, quotaStr] = process.argv;

if (!email) {
  console.error('Usage: npx tsx scripts/create-trial.ts <email> [quota]');
  process.exit(1);
}

const quotaMonth = parseInt(quotaStr ?? '5', 10);
if (isNaN(quotaMonth) || quotaMonth < 1) {
  console.error('quota must be a positive integer');
  process.exit(1);
}

function generateKey(): string {
  const part = () => randomBytes(2).toString('hex').toUpperCase();
  return `LAU-${part()}-${part()}-${part()}`;
}

function hashKey(key: string): string {
  return createHash('sha256').update(key).digest('hex');
}

function nextMonthReset(): string {
  const d = new Date();
  d.setMonth(d.getMonth() + 1);
  d.setDate(1);
  d.setHours(0, 0, 0, 0);
  return d.toISOString();
}

function trialExpiryDate(): string {
  const d = new Date();
  d.setDate(d.getDate() + 14);
  return d.toLocaleDateString('fr-FR');
}

const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY);

const key     = generateKey();
const keyHash = hashKey(key);

const { error } = await supabase.from('licences').insert({
  key_hash:    keyHash,
  email,
  plan:        'trial',
  quota_month: quotaMonth,
  usage_month: 0,
  reset_at:    nextMonthReset(),
  active:      true,
  allowed_ip:  null,
  flagged:     false,
});

if (error) {
  console.error('Supabase insert error:', error.message);
  process.exit(1);
}

const expiry = trialExpiryDate();

console.log('\nTrial licence created\n');
console.log(`  Key:         ${key}`);
console.log(`  Email:       ${email}`);
console.log(`  Quota:       ${quotaMonth} generations`);
console.log(`  Expires:     ${expiry} (manual deactivation required in Supabase)`);
console.log('\nStore the key now — it cannot be retrieved from the DB.\n');
console.log(`  Deactivate on ${expiry}:`);
console.log(`    UPDATE licences SET active=false WHERE key_hash='${keyHash}';\n`);
