#!/usr/bin/env node
/**
 * Seed the default local dev API key into Gateway Postgres (no tsx required).
 * Usage: node seed-gateway-api-key.cjs <gatewayBundlePath> <apiKey> [label]
 */

'use strict';

const { createRequire } = require('module');
const fs = require('fs');
const path = require('path');

function loadPrismaClient(bundlePath) {
  const req = createRequire(path.join(bundlePath, 'package.json'));
  try {
    return req('@prisma/client').PrismaClient;
  } catch {
    const generated = path.join(bundlePath, 'node_modules', '.prisma', 'client');
    if (fs.existsSync(path.join(generated, 'index.js'))) {
      return req(generated).PrismaClient;
    }
  }
  throw new Error(
    '@prisma/client not found in gateway bundle — run: cd apps/gateway && npm install && npm run db:generate',
  );
}

async function main() {
  const bundlePath = process.argv[2];
  const key = process.argv[3];
  const label = process.argv[4] || '4Runr OS dev';

  if (!bundlePath || !key) {
    console.error('Usage: node seed-gateway-api-key.cjs <gatewayBundlePath> <apiKey> [label]');
    process.exit(1);
  }

  if (!fs.existsSync(path.join(bundlePath, 'package.json'))) {
    console.error(`Gateway bundle not found: ${bundlePath}`);
    process.exit(1);
  }

  process.env.DATABASE_URL =
    process.env.DATABASE_URL ||
    'postgresql://4runr:4runr_dev_pass@localhost:5432/4runr_local';

  const PrismaClient = loadPrismaClient(bundlePath);
  const prisma = new PrismaClient();

  try {
    const existing = await prisma.apiKey.findUnique({ where: { key } });
    if (existing) {
      if (existing.revoked) {
        await prisma.apiKey.update({
          where: { key },
          data: { revoked: false, label },
        });
        console.log('reactivated');
      } else {
        console.log('exists');
      }
      return;
    }

    await prisma.apiKey.create({
      data: { key, label, revoked: false },
    });
    console.log('created');
  } finally {
    await prisma.$disconnect().catch(() => {});
  }
}

main().catch((err) => {
  console.error(err instanceof Error ? err.message : String(err));
  process.exit(1);
});
