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

interface AddMembershipRequest {
  category: string;
  amount: string;
  currency: string;
  paymentMethod: 'card' | 'twint';
  cardDetails?: {
    cardNumber: string;
    expiryDate: string;
    securityCode: string;
    cardholderName: string;
  };
}

export async function POST(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    
    if (!session?.user) {
      return NextResponse.json(
        { 
          success: false,
          error: 'Authentication required' 
        },
        { status: 401 }
      );
    }

    const body: AddMembershipRequest = await req.json();
    
    // Validate required fields
    if (!body.category || !body.amount || !body.currency || !body.paymentMethod) {
      return NextResponse.json(
        {
          success: false,
          error: 'Missing required fields: category, amount, currency, paymentMethod'
        },
        { status: 400 }
      );
    }

    // Validate card details for card payment
    if (body.paymentMethod === 'card') {
      if (!body.cardDetails || !body.cardDetails.cardNumber || !body.cardDetails.expiryDate || 
          !body.cardDetails.securityCode || !body.cardDetails.cardholderName) {
        return NextResponse.json(
          {
            success: false,
            error: 'Card details are required for card payment'
          },
          { status: 400 }
        );
      }
    }


    // Start database transaction
    const result = await prisma.$transaction(async (tx) => {
      // Find the category
      const category = await tx.category.findFirst({
        where: {
          OR: [
            { name: body.category },
            { slug: body.category }
          ]
        }
      });

      if (!category) {
        throw new Error(`Category '${body.category}' not found`);
      }

      // Check for existing active subscription in this category
      const existingSubscription = await tx.categorySubscription.findFirst({
        where: {
          userId: session.user.id,
          categoryId: category.id,
          status: 'ACTIVE',
          endDate: {
            gte: new Date()
          }
        }
      });

      if (existingSubscription) {
        throw new Error(`You already have an active membership for ${category.name}`);
      }

      // Create subscription dates
      const startDate = new Date();
      const endDate = new Date(startDate);
      endDate.setFullYear(endDate.getFullYear() + 1); // 1 year membership

      // Create category subscription
      const subscription = await tx.categorySubscription.create({
        data: {
          userId: session.user.id,
          categoryId: category.id,
          status: 'ACTIVE',
          startDate,
          endDate
        },
        include: {
          category: true
        }
      });

      // TODO: Integrate with Stripe payment processing
      // For now, we'll simulate successful payment
      const transactionId = `TXN${Date.now()}${Math.random().toString(36).substr(2, 6).toUpperCase()}`;

      return {
        id: subscription.id,
        transactionId,
        category: subscription.category.name,
        amount: parseFloat(body.amount),
        currency: body.currency,
        paymentMethod: body.paymentMethod,
        status: 'active',
        startDate: subscription.startDate.toISOString(),
        endDate: subscription.endDate.toISOString(),
        paymentStatus: 'completed'
      };
    });

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

  } catch (error) {
    console.error('Error adding membership:', error);
    
    // Handle specific error cases
    if (error instanceof Error) {
      if (error.message.includes('already have an active membership') || 
          error.message.includes('not found')) {
        return NextResponse.json(
          {
            success: false,
            error: error.message
          },
          { status: 400 }
        );
      }
    }

    // Handle JSON parsing errors
    if (error instanceof SyntaxError) {
      return NextResponse.json(
        {
          success: false,
          error: 'Invalid JSON in request body'
        },
        { status: 400 }
      );
    }
    
    return NextResponse.json(
      { 
        success: false,
        error: error instanceof Error ? error.message : 'Failed to add membership',
        type: 'server_error'
      },
      { status: 500 }
    );
  }
}