import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { systemMessagesAdapter } from "@/lib/adapters/system";
import { auth } from "@/lib/auth";

// Cache system messages for 1 hour - they rarely change
export const revalidate = 3600;

export async function GET(req: NextRequest) {
  try {
    const session = await auth();
    const userId = session?.user?.id;

    const now = new Date();

    // Fetch active messages
    const messages = await systemMessagesAdapter.findMany({
      where: {
        isActive: true,
        OR: [{ expiresAt: null }, { expiresAt: { gt: now } }],
      },
      orderBy: { createdAt: "desc" },
    });

    // Filter messages already viewed by logged-in user
    // If no user, we might rely on local storage on client side,
    // but server-side we return all and let client filter or record view.
    // Ideally, we mark view when user dismisses or sees it.

    // For authenticated users, we can filter out seen ones if desired,
    // but usually "System Alerts" should persist until dismissed explicitly or expired.
    // Let's return all active messages. The client will handle "dismissed" state
    // via localStorage (for guests) or DB (for users).

    return NextResponse.json(messages);
  } catch (error) {
    return NextResponse.json(
      { error: "Failed to fetch messages" },
      { status: 500 },
    );
  }
}

// POST: Mark as viewed
export async function POST(req: NextRequest) {
  try {
    const session = await auth();
    if (!session?.user?.id) {
      return NextResponse.json({ success: true }); // Ignore for guests
    }

    const { messageId } = await req.json();

    await prisma.system_message_views.upsert({
      where: {
        messageId_userId: {
          messageId,
          userId: session.user.id,
        },
      },
      update: {},
      create: {
        messageId,
        userId: session.user.id,
      },
    });

    return NextResponse.json({ success: true });
  } catch (error) {
    return NextResponse.json(
      { error: "Failed to track view" },
      { status: 500 },
    );
  }
}
