import { NextRequest, NextResponse } from "next/server";
import { db, users, userBlocks, userFollows, eq, and, or } from "@epicure/db";
import { requireSession } from "@/lib/api-auth";
import { applyRateLimit } from "@/lib/rate-limit";

type Params = { params: Promise<{ username: string }> };

export async function POST(_req: NextRequest, { params }: Params) {
  const { session, response } = await requireSession();
  if (response) return response;

  const limited = await applyRateLimit(`rl:block:${session!.user.id}`, 30, 60);
  if (limited) return limited;

  const { username } = await params;

  const target = await db.query.users.findFirst({ where: eq(users.username, username) });
  if (!target) return NextResponse.json({ error: "Not found" }, { status: 404 });
  if (target.id === session!.user.id) return NextResponse.json({ error: "Cannot block yourself" }, { status: 400 });

  await db.insert(userBlocks)
    .values({ blockerId: session!.user.id, blockedId: target.id })
    .onConflictDoNothing();

  // Blocking severs any existing follow relationship in either direction.
  await db.delete(userFollows).where(
    or(
      and(eq(userFollows.followerId, session!.user.id), eq(userFollows.followingId, target.id)),
      and(eq(userFollows.followerId, target.id), eq(userFollows.followingId, session!.user.id))
    )
  );

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

export async function DELETE(_req: NextRequest, { params }: Params) {
  const { session, response } = await requireSession();
  if (response) return response;

  const limited = await applyRateLimit(`rl:block:${session!.user.id}`, 30, 60);
  if (limited) return limited;

  const { username } = await params;

  const target = await db.query.users.findFirst({ where: eq(users.username, username) });
  if (!target) return NextResponse.json({ error: "Not found" }, { status: 404 });

  await db.delete(userBlocks).where(
    and(eq(userBlocks.blockerId, session!.user.id), eq(userBlocks.blockedId, target.id))
  );

  return NextResponse.json({ blocked: false });
}
