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?.email) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    // Get actual database user by email to ensure consistent user ID
    const dbUser = await prisma.user.findUnique({
      where: { email: session.user.email },
      select: { id: true, email: true }
    });

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

    const { searchParams } = new URL(req.url);
    const categoryId = searchParams.get('category');

    if (!prisma) {
      return NextResponse.json(
        { error: 'Database connection not available' },
        { status: 503 }
      );
    }

    try {
      if (categoryId) {
        // Check specific category subscription
        const subscription = await prisma.categorySubscription.findFirst({
          where: {
            userId: dbUser.id,
            categoryId: categoryId,
            status: 'ACTIVE',
            endDate: {
              gte: new Date()
            }
          },
          include: {
            category: {
              select: {
                name: true,
                slug: true
              }
            }
          }
        });

        const hasActiveMembership = !!subscription;
        
        return NextResponse.json({
          success: true,
          data: {
            hasActiveMembership,
            categoryId,
            categoryName: subscription?.category.name,
            membershipDetails: subscription ? {
              id: subscription.id,
              startDate: subscription.startDate.toISOString(),
              endDate: subscription.endDate.toISOString(),
              status: subscription.status
            } : null,
            permissions: {
              canBid: hasActiveMembership,
              canMessage: hasActiveMembership,
              canViewContacts: hasActiveMembership,
              maxBidsPerMonth: hasActiveMembership ? 50 : 0
            }
          }
        });
      } else {
        // Get all active subscriptions for user
        const subscriptions = await prisma.categorySubscription.findMany({
          where: {
            userId: dbUser.id,
            status: 'ACTIVE',
            endDate: {
              gte: new Date()
            }
          },
          include: {
            category: {
              select: {
                name: true,
                slug: true
              }
            }
          }
        });

        return NextResponse.json({
          success: true,
          data: {
            hasActiveMembership: subscriptions.length > 0,
            subscriptions: subscriptions.map(sub => ({
              id: sub.id,
              categoryId: sub.categoryId,
              categoryName: sub.category.name,
              categorySlug: sub.category.slug,
              startDate: sub.startDate.toISOString(),
              endDate: sub.endDate.toISOString(),
              status: sub.status
            })),
            permissions: {
              canBid: subscriptions.length > 0,
              canMessage: subscriptions.length > 0,
              canViewContacts: subscriptions.length > 0,
              maxBidsPerMonth: subscriptions.length > 0 ? 50 : 0
            }
          }
        });
      }
    } catch (dbError: any) {
      console.error('Database error:', dbError);
      
      return NextResponse.json(
        { 
          error: 'Database operation failed',
          message: 'Unable to check membership status due to a database error. Please try again later.',
          details: process.env.NODE_ENV === 'development' ? dbError.message : undefined
        },
        { status: 500 }
      );
    }

  } catch (error) {
    console.error('Error checking membership status:', error);
    return NextResponse.json(
      { 
        error: error instanceof Error ? error.message : 'Failed to check membership status',
        type: 'server_error'
      },
      { status: 500 }
    );
  }
}