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

interface RouteContext {
  params: Promise<{ id: string }>;
}

// GET /api/clients/[id]/membership - Get client's current membership (if any)
// This is a quick lookup endpoint for booking discount calculation
export async function GET(
  request: NextRequest,
  context: RouteContext
) {
  try {
    const session = await getServerSession(authOptions);

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

    const { id: clientId } = await context.params;

    // Verify client exists and belongs to organization
    const client = await db.client.findFirst({
      where: {
        id: clientId,
        organizationId: session.user.organizationId,
      },
      select: {
        id: true,
        firstName: true,
        lastName: true,
        email: true,
      },
    });

    if (!client) {
      return NextResponse.json(
        { error: 'Client not found' },
        { status: 404 }
      );
    }

    // Get client's active membership
    const now = new Date();

    const membership = await db.membership.findFirst({
      where: {
        clientId,
        status: 'ACTIVE',
        endDate: {
          gte: now,
        },
      },
      include: {
        plan: {
          select: {
            id: true,
            name: true,
            price: true,
            courtHours: true,
            discountPercent: true,
            benefits: true,
          },
        },
      },
      orderBy: {
        endDate: 'desc',
      },
    });

    // No active membership
    if (!membership) {
      return NextResponse.json({
        client,
        hasMembership: false,
        membership: null,
        discounts: {
          bookingDiscount: 0,
          storeDiscount: 0,
        },
      });
    }

    // Calculate discounts and remaining time
    const sevenDaysFromNow = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
    const daysUntilExpiry = Math.ceil((membership.endDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24));

    // Extract store discount from benefits array
    const storeDiscountBenefit = membership.plan.benefits?.find(b => b.includes('store discount'));
    const storeDiscount = storeDiscountBenefit
      ? parseInt(storeDiscountBenefit.match(/(\d+)%/)?.[1] || '0', 10)
      : 0;

    const response = {
      client,
      hasMembership: true,
      membership: {
        id: membership.id,
        planId: membership.plan.id,
        planName: membership.plan.name,
        startDate: membership.startDate,
        endDate: membership.endDate,
        status: membership.status,
        isExpiring: membership.endDate <= sevenDaysFromNow,
        daysUntilExpiry,
        autoRenew: membership.autoRenew,
      },
      benefits: {
        freeHours: membership.plan.courtHours || 0,
        hoursRemaining: membership.remainingHours || 0,
        hoursUsed: membership.plan.courtHours && membership.remainingHours !== null
          ? membership.plan.courtHours - membership.remainingHours
          : 0,
        extraBenefits: membership.plan.benefits || [],
      },
      discounts: {
        bookingDiscount: membership.plan.discountPercent ? Number(membership.plan.discountPercent) : 0,
        storeDiscount,
      },
    };

    return NextResponse.json(response);
  } catch (error) {
    console.error('Error fetching client membership:', error);
    return NextResponse.json(
      { error: 'Failed to fetch client membership' },
      { status: 500 }
    );
  }
}
