import { auth } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { redirect } from "next/navigation";
import { ProfileClient } from "@/components/profile/ProfileClient";

export const metadata = { title: "Mon Profil & Créateur - MTBR" };
export const dynamic = "force-dynamic";

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

  const userId = (session.user as any).id;

  const user = await prisma.user.findUnique({
    where: { id: userId },
    include: {
      transactions: { orderBy: { createdAt: "desc" } },
      favorites: {
        take: 12,
        orderBy: { createdAt: "desc" },
        include: { media: true }
      },
      watchHistory: {
        take: 12,
        orderBy: { createdAt: "desc" },
        include: { media: true }
      },
      _count: { select: { favorites: true, watchHistory: true, likes: true } },
    },
  });

  if (!user) redirect("/login");

  // Récupérer les médias postés par l'utilisateur
  let shorts: any[] = [];
  let longVideos: any[] = [];

  try {
    const userMediaRows: any[] = ((await prisma.$queryRawUnsafe(`
      SELECT 
        id, title, description, type, format, url, thumbnailUrl, 
        duration, views, isPremium, isPublished, uploaderId, tags, createdAt
      FROM "Media"
      WHERE uploaderId = ?
      ORDER BY createdAt DESC
      LIMIT 100
    `, userId).catch(() => [])) as any[]) || [];

    const formattedMedia = userMediaRows.map((m) => ({
      id: m.id,
      title: m.title,
      description: m.description,
      type: m.type,
      format: m.format || "LONG",
      url: m.url,
      thumbnailUrl: m.thumbnailUrl,
      duration: m.duration ? Number(m.duration) : null,
      views: m.views ? Number(m.views) : 0,
      isPremium: Boolean(m.isPremium),
      isPublished: Boolean(m.isPublished),
      uploaderId: m.uploaderId,
      tags: m.tags || "",
      createdAt: m.createdAt,
    }));

    shorts = formattedMedia.filter((m) => m.format === "SHORT");
    longVideos = formattedMedia.filter((m) => m.format !== "SHORT");
  } catch (err) {
    console.error("Error fetching user media:", err);
  }

  return (
    <div className="min-h-screen bg-[#050508] py-8 px-4 sm:px-6 lg:px-8">
      <div className="max-w-6xl mx-auto">
        <ProfileClient
          user={user}
          shorts={shorts}
          longVideos={longVideos}
          favorites={user.favorites}
          history={user.watchHistory}
        />
      </div>
    </div>
  );
}
