/**
 * Set up the GPU-as-API test account.
 *
 * Usage:
 *   npx tsx prisma/setup-test-account.ts
 *
 * Creates or updates brendonnc@yahoo.com with:
 * - emailVerified = now
 * - plan = "pro"
 * - A pre-generated API key for CLI testing
 */
import { PrismaClient } from "@prisma/client";
import bcrypt from "bcryptjs";
import { randomBytes } from "crypto";

const db = new PrismaClient();

const TEST_EMAIL = "brendonnc@yahoo.com";
const TEST_NAME = "Brendon";
const TEST_PASSWORD = process.env.TEST_PASSWORD || "LLMHosts2026!";

async function main() {
  const passwordHash = await bcrypt.hash(TEST_PASSWORD, 12);

  // Upsert the user
  const user = await db.user.upsert({
    where: { email: TEST_EMAIL },
    update: {
      name: TEST_NAME,
      emailVerified: new Date(),
      plan: "pro",
    },
    create: {
      email: TEST_EMAIL,
      name: TEST_NAME,
      passwordHash,
      emailVerified: new Date(),
      plan: "pro",
    },
  });

  console.log(`User: ${user.id} (${user.email}) plan=${user.plan}`);

  // Revoke any existing test key
  await db.apiKey.updateMany({
    where: { userId: user.id, name: "gpu-as-api-test", revokedAt: null },
    data: { revokedAt: new Date() },
  });

  // Create a fresh API key (stored raw, same as /api/keys route)
  const key = `lh_sk_${randomBytes(32).toString("base64url")}`;
  const prefix = key.substring(0, 12) + "...";

  const apiKey = await db.apiKey.create({
    data: {
      userId: user.id,
      name: "gpu-as-api-test",
      key,
      prefix,
    },
  });

  console.log(`API Key: ${apiKey.id} (name=${apiKey.name})`);
  console.log(`\nRaw API key (save this — shown only once):\n  ${key}\n`);
  console.log("Test account ready. Use this key with:");
  console.log(`  export OPENAI_API_KEY=${key}`);
  console.log(`  export OPENAI_BASE_URL=https://llmhosts.com/api/relay/v1`);
}

main()
  .catch((e) => {
    console.error("Setup failed:", e);
    process.exit(1);
  })
  .finally(() => db.$disconnect());
