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(
        { 
          success: false,
          error: 'Authentication required',
          message: 'Please log in to view your membership information.'
        },
        { 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(
        { 
          success: false,
          error: 'User not found in database',
          message: 'Your user account was not found. Please contact support.'
        },
        { status: 404 }
      );
    }

    // Fetch active category subscriptions for the user
    const categorySubscriptions = await prisma.categorySubscription.findMany({
      where: {
        userId: dbUser.id,
        status: {
          in: ['ACTIVE', 'EXPIRED']
        }
      },
      include: {
        category: true
      },
      orderBy: {
        endDate: 'desc'
      }
    });

    // Transform database results to API format
    const memberships = categorySubscriptions.map(subscription => {
      const now = new Date();
      const endDate = new Date(subscription.endDate);
      const diffTime = endDate.getTime() - now.getTime();
      const expiryDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
      
      let status: 'active' | 'expired' | 'expiring' = 'expired';
      if (subscription.status === 'ACTIVE') {
        if (expiryDays > 7) {
          status = 'active';
        } else if (expiryDays > 0) {
          status = 'expiring';
        }
      }

      return {
        id: subscription.id,
        category: subscription.category.name,
        icon: subscription.category.icon || `/assets/image/category/${subscription.category.slug}.svg`,
        status,
        startDate: subscription.startDate.toISOString(),
        endDate: subscription.endDate.toISOString(),
        expiryDays: Math.max(0, expiryDays)
      };
    });

    return NextResponse.json({
      success: true,
      message: 'Membership data loaded successfully',
      data: memberships
    });

  } catch (error) {
    console.error('Error fetching memberships:', error);
    
    return NextResponse.json(
      { 
        success: false,
        error: 'Failed to load membership data',
        message: 'We encountered an issue loading your membership information. Please try refreshing the page or contact support if the problem persists.',
        details: error instanceof Error ? error.message : 'Unknown server error',
        type: 'server_error'
      },
      { status: 500 }
    );
  }
}