import { requireAuth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { getUserTier, DAILY_LIMITS } from "@/lib/tiers";

export const runtime = "nodejs";

export async function GET(request: Request) {
  try {
    const user = await requireAuth(request);
    if (!user) {
      return Response.json({ error: "Unauthorized" }, { status: 401 });
    }

    const dbUser = await prisma.user.findUnique({
      where: { id: user.userId },
      select: {
        dailyMsgCount: true,
        dailyMsgResetAt: true,
        isPremium: true,
        isPro: true,
      },
    });

    if (!dbUser) {
      return Response.json({ error: "User not found" }, { status: 404 });
    }

    const tier = getUserTier(dbUser.isPremium, dbUser.isPro);
    const limits = DAILY_LIMITS[tier];

    const now = new Date();
    let count = dbUser.dailyMsgCount;
    let resetAt = dbUser.dailyMsgResetAt;

    // Reset if new day
    if (!resetAt || now.getTime() - resetAt.getTime() > 24 * 60 * 60 * 1000) {
      count = 0;
      resetAt = now;
    }

    return Response.json({
      count,
      limit: limits.msgs === Infinity ? -1 : limits.msgs,
      resetAt: resetAt?.toISOString() || now.toISOString(),
      tier,
      remaining:
        limits.msgs === Infinity ? -1 : Math.max(0, limits.msgs - count),
    });
  } catch (error) {
    console.error("Daily chat error:", error);
    return Response.json({ error: "Internal server error" }, { status: 500 });
  }
}
