import { NextResponse } from "next/server";
import { db } from "@/lib/db";
import { gradientFor } from "@/lib/poster";

export const dynamic = "force-dynamic";

export async function GET() {
  const [artists, albums, tracks] = await Promise.all([
    db.musicArtist.findMany({
      include: { _count: { select: { albums: true, tracks: true } } },
      orderBy: { monthlyListeners: "desc" },
    }),
    db.musicAlbum.findMany({
      include: { artist: true, _count: { select: { tracks: true } } },
      orderBy: { createdAt: "desc" },
    }),
    db.musicTrack.findMany({
      include: { artist: true, album: true },
      orderBy: { plays: "desc" },
      take: 30,
    }),
  ]);

  return NextResponse.json({
    artists: artists.map((a) => ({
      id: a.id,
      slug: a.slug,
      name: a.name,
      persianName: a.persianName,
      photo: a.photo,
      bio: a.bio,
      verified: a.verified,
      monthlyListeners: a.monthlyListeners,
      gradient: a.photo ? ["#000", "#000"] : gradientFor(a.slug),
      albumsCount: a._count.albums,
      tracksCount: a._count.tracks,
    })),
    albums: albums.map((al) => ({
      id: al.id,
      slug: al.slug,
      title: al.title,
      persianTitle: al.persianTitle,
      year: al.year,
      genre: al.genre,
      cover: al.cover,
      coverColors: al.coverColor1 && al.coverColor2 ? [al.coverColor1, al.coverColor2] : gradientFor(al.slug),
      artist: { id: al.artist.id, slug: al.artist.slug, name: al.artist.name, persianName: al.artist.persianName },
      tracksCount: al._count.tracks,
    })),
    tracks: tracks.map((t) => ({
      id: t.id,
      slug: t.slug,
      title: t.title,
      audioUrl: t.audioUrl,
      duration: t.duration,
      plays: t.plays,
      genre: t.genre,
      isExplicit: t.isExplicit,
      cover: t.cover,
      coverColors: t.coverColor1 && t.coverColor2 ? [t.coverColor1, t.coverColor2] : gradientFor(t.slug),
      artist: { id: t.artist.id, slug: t.artist.slug, name: t.artist.name, persianName: t.artist.persianName },
      album: t.album ? { id: t.album.id, slug: t.album.slug, title: t.album.title } : null,
    })),
  });
}
