#!/usr/bin/env npx tsx
/**
 * Admin script: create a NoteToQuote licence in Supabase.
 *
 * Usage:
 *   npx tsx scripts/create-licence.ts <email> <plan> <quota_month> [allowed_ip]
 *
 * Plans:    starter (50/month)  pro (500/month)  agency (unlimited → use 99999)
 * Example:
 *   npx tsx scripts/create-licence.ts client@example.com pro 500
 *   npx tsx scripts/create-licence.ts partner@acme.com   agency 99999 192.168.1.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, plan, quotaStr, allowedIp] = process.argv;

if (!email || !plan || !quotaStr) {
  console.error('Usage: npx tsx scripts/create-licence.ts <email> <plan> <quota_month> [allowed_ip]');
  process.exit(1);
}

const quotaMonth = parseInt(quotaStr, 10);
if (isNaN(quotaMonth) || quotaMonth < 1) {
  console.error('quota_month 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();
}

const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY);

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

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

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

console.log('\nLicence created successfully\n');
console.log(`  Key:          ${key}`);
console.log(`  Email:        ${email}`);
console.log(`  Plan:         ${plan}`);
console.log(`  Quota/month:  ${quotaMonth}`);
console.log(`  Allowed IP:   ${allowedIp ?? '(any)'}`);
console.log(`  Resets at:    ${resetAt}`);
console.log('\nStore the key now — it cannot be retrieved from the DB (only the hash is stored).\n');
