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

const MAX_LENGTH = 180;

export async function POST(request: Request) {
  try {
    const body = (await request.json()) as {
      path?: string;
      referrer?: string;
      language?: string;
      timezone?: string;
      deviceType?: string;
      viewport?: string;
    };

    const path = cleanPath(body.path);
    if (!path) {
      return NextResponse.json({ ok: false }, { status: 400 });
    }

    await prisma.siteVisit.create({
      data: {
        path,
        referrerHost: cleanReferrer(body.referrer),
        language: cleanText(body.language),
        timezone: cleanText(body.timezone),
        deviceType: cleanText(body.deviceType),
        viewport: cleanText(body.viewport),
      },
    });

    return NextResponse.json({ ok: true });
  } catch {
    return NextResponse.json({ ok: false }, { status: 400 });
  }
}

function cleanPath(value: unknown) {
  if (typeof value !== "string") return null;
  if (!value.startsWith("/")) return null;
  if (value.includes("?")) return value.split("?")[0].slice(0, MAX_LENGTH);
  return value.slice(0, MAX_LENGTH);
}

function cleanReferrer(value: unknown) {
  if (typeof value !== "string" || !value) return null;
  try {
    const url = new URL(value);
    if (url.hostname === "toolaro.org" || url.hostname === "www.toolaro.org") return "direct/internal";
    return url.hostname.slice(0, MAX_LENGTH);
  } catch {
    return null;
  }
}

function cleanText(value: unknown) {
  if (typeof value !== "string" || !value) return null;
  return value.slice(0, MAX_LENGTH);
}
