// app/api/admin/notifications/route.ts
import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth-options';
import { prisma } from '@/lib/prisma';

export async function GET(req: Request) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.email) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const role = (session as any)?.user?.role ?? null;
    if (!(role === 'admin' || role === 'superadmin')) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    // Get current user
    const user = await prisma.user.findUnique({
      where: { email: session.user.email },
      select: { id: true },
    });

    if (!user) {
      return NextResponse.json({ error: 'User not found' }, { status: 404 });
    }

    // Get all videos uploaded by this admin or superadmin
    const uploadedVideos = await prisma.video.findMany({
      where: { userId: user.id },
      select: { id: true, title: true },
    });

    const videoIds = uploadedVideos.map((v) => v.id);

    if (videoIds.length === 0) {
      return NextResponse.json({
        likes: [],
        comments: [],
        total: 0,
      });
    }

    // Fetch recent likes on uploaded videos
    const likes = await prisma.videoLike.findMany({
      where: { videoId: { in: videoIds } },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            image: true,
            email: true,
          },
        },
        video: {
          select: {
            id: true,
            title: true,
          },
        },
      },
      orderBy: { createdAt: 'desc' },
      take: 50,
    });

    // Fetch recent comments on uploaded videos
    const comments = await prisma.comment.findMany({
      where: { videoId: { in: videoIds } },
      include: {
        user: {
          select: {
            id: true,
            name: true,
            image: true,
            email: true,
          },
        },
        video: {
          select: {
            id: true,
            title: true,
          },
        },
      },
      orderBy: { createdAt: 'desc' },
      take: 50,
    });

    // Fetch recently created courses by this user
    const createdCourses = await prisma.course.findMany({
      where: { userId: user.id },
      select: {
        id: true,
        title: true,
        code: true,
        createdAt: true,
      },
      orderBy: { createdAt: 'desc' },
      take: 50,
    });

    // Fetch recently created playlists by this user
    const createdPlaylists = await prisma.playlist.findMany({
      where: { userId: user.id },
      include: {
        course: {
          select: {
            id: true,
            title: true,
          },
        },
      },
      orderBy: { createdAt: 'desc' },
      take: 50,
    });

    // Combine and sort by date
    const allNotifications = [
      ...likes.map((like) => ({
        id: like.id,
        type: 'like' as const,
        user: like.user,
        video: like.video,
        content: null,
        createdAt: like.createdAt,
      })),
      ...comments.map((comment) => ({
        id: comment.id,
        type: 'comment' as const,
        user: comment.user,
        video: comment.video,
        content: comment.content,
        createdAt: comment.createdAt,
      })),
      ...createdCourses.map((course) => ({
        id: course.id,
        type: 'course_created' as const,
        user: null,
        course: { id: course.id, title: course.title, code: course.code },
        content: null,
        createdAt: course.createdAt,
      })),
      ...createdPlaylists.map((playlist) => ({
        id: playlist.id,
        type: 'playlist_created' as const,
        user: null,
        playlist: { id: playlist.id, title: playlist.title, courseTitle: playlist.course.title },
        content: null,
        createdAt: playlist.createdAt,
      })),
    ].sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());

    return NextResponse.json({
      likes,
      comments,
      notifications: allNotifications,
      total: allNotifications.length,
    });
  } catch (err: any) {
    console.error('get notifications error', err);
    return NextResponse.json(
      { error: err?.message ?? 'server error' },
      { status: 500 }
    );
  }
}
