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

export const dynamic = "force-dynamic";

export async function GET(req: NextRequest) {
  try {
    const session = await auth();
    const role = (session?.user as any)?.role;
    if (!["ADMIN", "SUPERADMIN", "MODERATOR"].includes(role)) {
      return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
    }

    const { searchParams } = new URL(req.url);
    const search = searchParams.get("search") || "";
    const page = Math.max(1, parseInt(searchParams.get("page") || "1"));
    const limit = Math.min(100, Math.max(10, parseInt(searchParams.get("limit") || "25")));
    const skip = (page - 1) * limit;

    const where: any = {};
    if (search.trim()) {
      where.OR = [
        { name: { contains: search.trim() } },
        { email: { contains: search.trim() } }
      ];
    }

    const [users, total, vipCount, adminCount] = await Promise.all([
      prisma.user.findMany({
        where,
        orderBy: { createdAt: "desc" },
        skip,
        take: limit,
        select: {
          id: true,
          name: true,
          email: true,
          image: true,
          role: true,
          isPremium: true,
          isVerified: true,
          isBanned: true,
          createdAt: true,
          lastLogin: true,
          _count: { select: { uploadedMedia: true, comments: true } }
        }
      }),
      prisma.user.count({ where }),
      prisma.user.count({ where: { isPremium: true } }),
      prisma.user.count({ where: { role: { in: ["ADMIN", "SUPERADMIN", "MODERATOR"] } } })
    ]);

    return NextResponse.json({
      users,
      pagination: {
        total,
        page,
        limit,
        totalPages: Math.ceil(total / limit)
      },
      stats: {
        total,
        vipCount,
        adminCount,
        freeCount: total - vipCount
      }
    });
  } catch (error: any) {
    console.error("Error in GET /api/admin/users:", error);
    return NextResponse.json({ error: error.message || "Erreur serveur" }, { status: 500 });
  }
}

export async function PUT(req: Request) {
  try {
    const session = await auth();
    const role = (session?.user as any)?.role;
    if (!["ADMIN", "SUPERADMIN"].includes(role)) {
      return NextResponse.json({ error: "Non autorisé" }, { status: 401 });
    }

    const body = await req.json();
    const { id, role: newRole, isPremium, isVerified, isBanned, action } = body;

    // Action spéciale : Nettoyer tous les faux comptes générés
    if (action === "cleanup_fakes") {
      const adminUser = await prisma.user.findFirst({ where: { role: "ADMIN" } });
      const adminId = adminUser?.id || "cmrs0m7bn000011pd6gd2m8q8";

      // Réassigner les vidéos pour ne rien perdre
      await prisma.$executeRawUnsafe(
        `UPDATE "Media" SET "uploaderId" = ? WHERE "uploaderId" IN (SELECT "id" FROM "User" WHERE "email" LIKE '%streamvibe.local%');`,
        adminId
      ).catch(() => {});

      // Supprimer les faux comptes
      const deleted = await prisma.$executeRawUnsafe(
        `DELETE FROM "User" WHERE "email" LIKE '%streamvibe.local%';`
      ).catch(() => 0);

      return NextResponse.json({ success: true, deletedCount: deleted });
    }

    if (!id) {
      return NextResponse.json({ error: "ID requis" }, { status: 400 });
    }

    if (action === "delete") {
      // Reassigner les uploads éventuels à l'admin avant suppression
      const adminUser = await prisma.user.findFirst({ where: { role: "ADMIN" } });
      if (adminUser) {
        await prisma.media.updateMany({
          where: { uploaderId: id },
          data: { uploaderId: adminUser.id }
        }).catch(() => {});
      }

      await prisma.user.delete({ where: { id } });
      return NextResponse.json({ success: true, deleted: true });
    }

    const updateData: any = {};
    if (newRole !== undefined) updateData.role = newRole;
    if (isPremium !== undefined) updateData.isPremium = Boolean(isPremium);
    if (isVerified !== undefined) updateData.isVerified = Boolean(isVerified);
    if (isBanned !== undefined) updateData.isBanned = Boolean(isBanned);

    const updated = await prisma.user.update({
      where: { id },
      data: updateData
    });

    return NextResponse.json(updated);
  } catch (error: any) {
    console.error("Error in PUT /api/admin/users:", error);
    return NextResponse.json({ error: error.message || "Erreur serveur" }, { status: 500 });
  }
}
