import { NextResponse } from "next/server";
import bcrypt from "bcryptjs";
import { prisma } from "@/lib/prisma";

export async function GET() {
  try {
    const testEmail = "test.premium2@example.com";
    const testPassword = "TestPassword123!";

    let user = await prisma.user.findUnique({
      where: { email: testEmail },
    });

    if (!user) {
      const passwordHash = await bcrypt.hash(testPassword, 10);
      user = await prisma.user.create({
        data: {
          email: testEmail,
          name: "Test Premium User 2",
          passwordHash,
          plan: "PREMIUM",
          emailVerified: new Date(),
          stripeId: "cus_test_" + Date.now(),
          subscription: {
            create: {
              stripeId: "sub_test_" + Date.now(),
              stripePriceId: "price_test",
              stripeCustomerId: "cus_test_" + Date.now(),
              status: "active",
              currentPeriodEnd: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
            },
          },
        },
        include: { subscription: true },
      });
    } else {
      // Reset the existing user to premium status
      await prisma.user.update({
        where: { id: user.id },
        data: {
          plan: "PREMIUM",
          emailVerified: new Date(),
        },
      });

      const sub = await prisma.subscription.findUnique({ where: { userId: user.id } });
      if (!sub) {
        await prisma.subscription.create({
          data: {
            userId: user.id,
            stripeId: "sub_test_" + Date.now(),
            stripePriceId: "price_test",
            stripeCustomerId: "cus_test_" + Date.now(),
            status: "active",
            currentPeriodEnd: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
          },
        });
      } else {
        await prisma.subscription.update({
          where: { userId: user.id },
          data: {
            status: "active",
            canceledAt: null,
            currentPeriodEnd: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
          },
        });
      }
    }

    return NextResponse.json({
      email: testEmail,
      password: testPassword,
      plan: user.plan,
      hasSubscription: !!user.stripeId,
    });
  } catch (error) {
    console.error("[test] error", error);
    return NextResponse.json(
      { error: "Failed to create test user" },
      { status: 500 }
    );
  }
}
