import { redirect } from "next/navigation";
import { auth } from "@/lib/auth";
import prisma from "@/lib/prisma";
import Link from "next/link";

export default async function SubscribedGalleriesPage() {
  const session = await auth();
  if (!session?.user) redirect("/login");

  // Galleries are purchased, not subscribed to via the Subscription model.
  // Query purchases where purchasable_type is Gallery.
  const purchases = await prisma.purchase.findMany({
    where: { user_id: Number(session.user.id), purchasable_type: "App\\Models\\Gallery" },
    include: {
      gallery: {
        select: { id: true, name: true, user: { select: { username: true } } },
      },
    },
    orderBy: { created_at: "desc" },
  });

  return (
    <div className="max-w-3xl mx-auto">
      <h1 className="text-3xl font-bold text-text mb-6">Purchased Galleries</h1>

      {purchases.length === 0 ? (
        <div className="bg-surface rounded-lg p-12 text-center">
          <p className="text-text-muted mb-4">You have not purchased any galleries yet.</p>
          <Link href="/galleries" className="text-primary hover:text-primary-dark font-semibold">
            Browse galleries
          </Link>
        </div>
      ) : (
        <div className="space-y-3">
          {purchases.map((purchase) => (
            <div key={purchase.id} className="bg-surface rounded-lg p-4 flex items-center justify-between">
              <div>
                <Link
                  href={`/gallery/show/${purchase.gallery?.id}`}
                  className="font-semibold text-text hover:text-primary transition-colors"
                >
                  {purchase.gallery?.name || "Untitled"}
                </Link>
                <p className="text-text-muted text-sm">
                  By {purchase.gallery?.user?.username || "Unknown"}
                </p>
              </div>
              <Link
                href={`/gallery/show/${purchase.gallery?.id}`}
                className="text-primary hover:text-primary-dark text-sm"
              >
                View Gallery
              </Link>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
