import { NextResponse } from "next/server";
import { getClientIp, hasPremium, requireUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { hashIp } from "@/lib/security";

export async function GET() {
  const user = await requireUser();
  return NextResponse.json({
    ok: true,
    history: await prisma.toolUsage.findMany({ where: { userId: user.id }, orderBy: { createdAt: "desc" }, take: 50 }),
  });
}

export async function POST(request: Request) {
  const user = await requireUser();
  if (!user.historyEnabled || !hasPremium(user)) return NextResponse.json({ ok: true, skipped: true });
  const body = (await request.json()) as { toolSlug?: string };
  const toolSlug = String(body.toolSlug ?? "").trim();
  if (!toolSlug) return NextResponse.json({ ok: false }, { status: 400 });
  await prisma.toolUsage.create({ data: { userId: user.id, toolSlug, ipHash: hashIp(getClientIp()) } });
  return NextResponse.json({ ok: true });
}

export async function DELETE() {
  const user = await requireUser();
  await prisma.toolUsage.deleteMany({ where: { userId: user.id } });
  return NextResponse.json({ ok: true });
}
