import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";

export async function GET(_req: NextRequest) {
  const start = Date.now();

  try {
    // Enforce 3-second max runtime
    if (Date.now() - start >= 3000) {
      return NextResponse.json(
        { status: "error", reads: false, writes: false, error: "Timeout" },
        { status: 504 }
      );
    }

    // 1. Test read: count users (SELECT COUNT(*) FROM User)
    let userCount: number;
    try {
      userCount = await prisma.user.count();
    } catch (readErr) {
      const message = readErr instanceof Error ? readErr.message : "Read query failed";
      return NextResponse.json(
        { status: "error", reads: false, writes: false, error: message },
        { status: 503 }
      );
    }

    // 2. Test write: insert a lightweight temp record and delete it immediately
    try {
      const testId = `health-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
      const testEmail = `${testId}@health.internal`;

      await prisma.$executeRawUnsafe(
        `INSERT INTO User (id, email, name, flhBalance) VALUES (?, ?, ?, ?)`,
        testId,
        testEmail,
        "__health_check__",
        0
      );

      // Clean up — this record must not persist
      await prisma.$executeRawUnsafe(`DELETE FROM User WHERE id = ?`, testId);
    } catch (writeErr) {
      const message = writeErr instanceof Error ? writeErr.message : "Write query failed";
      return NextResponse.json(
        { status: "error", reads: false, writes: false, error: message },
        { status: 503 }
      );
    }

    // 3. All checks passed
    return NextResponse.json({
      status: "ok",
      reads: true,
      writes: true,
      count: userCount,
    });
  } catch (err) {
    const message = err instanceof Error ? err.message : "Unknown error";
    return NextResponse.json(
      { status: "error", reads: false, writes: false, error: message },
      { status: 500 }
    );
  }
}
