import { and, desc, eq } from "drizzle-orm";
import { NextResponse } from "next/server";

import { auth } from "@/lib/auth";
import { getActiveOrgIdFromSession } from "@/lib/auth-guards";
import { db } from "@/lib/db";
import { sites, siteTests } from "@/lib/db/schema";

// GET /api/sites/:siteId — get site with all tests
export async function GET(req: Request, { params }: { params: Promise<{ siteId: string }> }) {
  const session = await auth.api.getSession({ headers: req.headers });
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const orgId = await getActiveOrgIdFromSession(session);
  if (!orgId) return NextResponse.json({ error: "No active organization" }, { status: 400 });

  const { siteId } = await params;

  const site = (
    await db
      .select()
      .from(sites)
      .where(and(eq(sites.id, siteId), eq(sites.organizationId, orgId)))
      .limit(1)
  )[0];

  if (!site) return NextResponse.json({ error: "Not found" }, { status: 404 });

  const tests = await db
    .select()
    .from(siteTests)
    .where(eq(siteTests.siteId, siteId))
    .orderBy(desc(siteTests.createdAt));

  return NextResponse.json({ ...site, tests });
}

// DELETE /api/sites/:siteId
export async function DELETE(req: Request, { params }: { params: Promise<{ siteId: string }> }) {
  const session = await auth.api.getSession({ headers: req.headers });
  if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const orgId = await getActiveOrgIdFromSession(session);
  if (!orgId) return NextResponse.json({ error: "No active organization" }, { status: 400 });

  const { siteId } = await params;
  await db.delete(sites).where(and(eq(sites.id, siteId), eq(sites.organizationId, orgId)));

  return NextResponse.json({ deleted: true });
}
