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

import { db } from "@/lib/db";
import { siteTests } from "@/lib/db/schema";
import { validateIntegrationBearer } from "@/lib/integration-auth";
import { getClientIp, rateLimit } from "@/lib/rate-limit";
import { launchSitespeedTest } from "@/lib/sitespeed-launch";

const PUBLIC_URL = process.env.BETTER_AUTH_URL || "http://localhost:3000";

const bodySchema = z.object({
  url: z.string().min(1),
  device: z.enum(["desktop", "mobile"]).optional(),
});

export async function POST(req: Request) {
  const authCheck = validateIntegrationBearer(req.headers.get("authorization"));
  if (!authCheck.ok) {
    return NextResponse.json({ error: authCheck.message }, { status: authCheck.status });
  }

  const ip = getClientIp(req.headers);
  const rl = rateLimit(`audit:${ip}`, { max: 10, windowMs: 60_000 });
  if (!rl.ok) {
    return NextResponse.json(
      { error: "rate_limited", message: `Retry in ${rl.retryAfter}s` },
      { status: 429, headers: { "Retry-After": String(rl.retryAfter) } },
    );
  }

  const parsed = bodySchema.safeParse(await req.json().catch(() => ({})));
  if (!parsed.success) {
    return NextResponse.json(
      { error: "invalid_body", details: parsed.error.issues },
      { status: 400 },
    );
  }

  const { url: rawUrl, device = "desktop" } = parsed.data;
  const fullUrl = rawUrl.startsWith("http") ? rawUrl : `https://${rawUrl}`;
  let hostname: string;
  try {
    hostname = new URL(fullUrl).hostname;
  } catch {
    return NextResponse.json({ error: "invalid_url" }, { status: 400 });
  }

  // Dedupe: anonymous audit already exists for this hostname → require auth.
  const existing = await db
    .select({ id: siteTests.id, status: siteTests.status })
    .from(siteTests)
    .where(and(eq(siteTests.hostname, hostname), isNull(siteTests.triggeredByUserId)))
    .limit(1);

  if (existing.length > 0) {
    return NextResponse.json(
      {
        error: "auth_required",
        message: `Site ${hostname} a déjà été audité anonymement. Créez un compte pour relancer un audit.`,
        signupUrl: `${PUBLIC_URL}/signup`,
        existingAuditId: existing[0].id,
        existingAuditStatus: existing[0].status,
      },
      { status: 403 },
    );
  }

  // siteId, organizationId, triggeredByUserId all stay null — anonymous audit.
  const result = await launchSitespeedTest({
    url: fullUrl,
    hostname,
    device,
    siteId: null,
    organizationId: null,
    triggeredByUserId: null,
  });

  if (!result.ok) {
    return NextResponse.json(
      { error: "sitespeed_error", message: result.error },
      { status: result.status },
    );
  }

  return NextResponse.json({ id: result.id, status: result.status, hostname }, { status: 202 });
}
