import { NextRequest, NextResponse } from "next/server";
import { db } from "@/lib/db";
import { hashToken, revokeRefreshTokenFamily } from "@/lib/mobileTokens";

export async function POST(req: NextRequest) {
  const authHeader = req.headers.get("authorization");
  const accessToken = authHeader?.match(/^Bearer\s+(.+)$/i)?.[1];
  const { refreshToken } = await req.json().catch(() => ({}));

  if (accessToken) {
    await db.session.deleteMany({
      where: { sessionToken: accessToken },
    });
  }

  if (typeof refreshToken === "string" && refreshToken.trim()) {
    const token = await db.refreshToken.findUnique({
      where: { tokenHash: hashToken(refreshToken.trim()) },
      select: { userId: true, familyId: true },
    });

    if (token) {
      await revokeRefreshTokenFamily(token.userId, token.familyId);
    }
  }

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