import { NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { Role } from "@/prisma/generated/prisma/client";
import { readdir } from "fs/promises";
import { join } from "path";
import { existsSync } from "fs";

export async function GET() {
  try {
    const session = await auth();

    if (!session?.user || session.user.role !== Role.ADMIN) {
      return NextResponse.json({ error: "Accès refusé" }, { status: 403 });
    }

    const images: string[] = [];

    // Lister uniquement les images dans public/uploads/backgrounds/
    const publicDir = join(process.cwd(), "public");
    const uploadsDir = join(publicDir, "uploads");
    const backgroundsDir = join(uploadsDir, "backgrounds");

    if (existsSync(backgroundsDir)) {
      const files = await readdir(backgroundsDir);
      const imageFiles = files.filter(
        (file) =>
          file.match(/\.(jpg|jpeg|png|gif|webp|svg)$/i) && !file.startsWith(".")
      );
      images.push(...imageFiles.map((file) => `/api/backgrounds/${file}`));
    }

    return NextResponse.json({ images });
  } catch (error) {
    console.error("Error listing images:", error);
    return NextResponse.json(
      { error: "Erreur lors de la récupération des images" },
      { status: 500 }
    );
  }
}
