import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';

export async function GET(_req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);

    if (!session?.user?.id) {
      return NextResponse.json({ success: false, error: 'Unauthorized' }, { status: 401 });
    }

    if (!prisma) {
      return NextResponse.json({ success: true, data: [] });
    }

    const subs = await prisma.categorySubscription.findMany({
      where: {
        userId: session.user.id,
        status: 'ACTIVE',
        endDate: { gte: new Date() },
      },
      select: {
        category: {
          select: { id: true, name: true, slug: true, icon: true },
        },
      },
      orderBy: { createdAt: 'desc' },
    });

    const categories = subs
      .map((s) => s.category)
      .filter(Boolean)
      .sort((a, b) => a!.name.localeCompare(b!.name));

    return NextResponse.json({ success: true, data: categories });
  } catch (error) {
    console.error('Error fetching subscribed categories:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to fetch subscribed categories' },
      { status: 500 }
    );
  }
}

