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) {
      return NextResponse.json(
        { 
          success: false,
          error: 'Authentication required',
          message: 'Please log in to view your membership history.'
        },
        { status: 401 }
      );
    }

    // Get query parameters
    const { searchParams } = new URL(req.url);
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '10');
    const statusFilter = searchParams.get('status') || 'all';
    const dateRange = searchParams.get('dateRange');

    // Build where clause for filtering
    let whereClause: any = {
      userId: session.user.id
    };

    // Apply status filter
    if (statusFilter && statusFilter !== 'all') {
      const statusMap: { [key: string]: string } = {
        'active': 'ACTIVE',
        'expired': 'EXPIRED',
        'cancelled': 'CANCELLED'
      };
      whereClause.status = statusMap[statusFilter] || 'ACTIVE';
    }

    // Apply date range filter
    if (dateRange) {
      const [startDate, endDate] = dateRange.split(',');
      if (startDate && endDate) {
        whereClause.createdAt = {
          gte: new Date(startDate),
          lte: new Date(endDate)
        };
      }
    }

    // Get total count for pagination
    const totalCount = await prisma.categorySubscription.count({
      where: whereClause
    });

    // Fetch subscriptions with pagination
    const subscriptions = await prisma.categorySubscription.findMany({
      where: whereClause,
      include: {
        category: true,
        // TODO: Include payment information when Payment model is properly linked
      },
      orderBy: {
        createdAt: 'desc'
      },
      skip: (page - 1) * limit,
      take: limit
    });

    // Transform data to match API format
    const transactions = subscriptions.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';
        }
      }

      // Generate transaction ID (this should come from payment records in production)
      const transactionId = `TXN${subscription.createdAt.getFullYear()}${String(subscription.createdAt.getMonth() + 1).padStart(2, '0')}${String(subscription.createdAt.getDate()).padStart(2, '0')}${subscription.id.slice(-6)}`;

      return {
        id: subscription.id,
        transactionId,
        category: subscription.category.name,
        categoryIcon: subscription.category.icon || `/assets/image/category/${subscription.category.slug}.svg`,
        // TODO: Get actual amount from payment records
        amount: 149.90, // Default amount, should come from payment
        currency: 'EUR', // Default currency, should come from payment
        paymentMethod: 'card', // Default method, should come from payment
        status,
        paymentStatus: 'completed',
        date: subscription.createdAt.toISOString(),
        startDate: subscription.startDate.toISOString(),
        endDate: subscription.endDate.toISOString()
      };
    });

    // Calculate pagination
    const totalPages = Math.ceil(totalCount / limit);
    const hasNext = page < totalPages;
    const hasPrev = page > 1;

    return NextResponse.json({
      success: true,
      message: `Found ${totalCount} membership record${totalCount !== 1 ? 's' : ''}`,
      data: {
        transactions,
        pagination: {
          currentPage: page,
          totalPages,
          totalItems: totalCount,
          itemsPerPage: limit,
          hasNextPage: hasNext,
          hasPrevPage: hasPrev
        }
      }
    });

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