import { NextRequest, NextResponse } from 'next/server';
import { dbConnect } from '@/lib/dbConnect';
import { Subscription } from '@/models/Subscription';
import { requireAdmin } from '@/lib/auth';
import { validateFields } from '@/lib/validation';

interface Params {
  params: { id: string };
}

// POST /api/subscriptions/[id]/extend - Admin manually extends subscription expiry
export async function POST(req: NextRequest, { params }: Params) {
  const auth = requireAdmin(req);
  if (auth instanceof NextResponse) return auth;

  try {
    await dbConnect();
    const body = await req.json();

    const { newExpiryDate, extendDays, extendMonths, reason } = body;

    const subscription = await Subscription.findById(params.id);
    if (!subscription) {
      return NextResponse.json({ success: false, error: 'Subscription not found' }, { status: 404 });
    }

    const previousExpiryDate = new Date(subscription.expiryDate);
    let updatedExpiryDate: Date;

    if (newExpiryDate) {
      updatedExpiryDate = new Date(newExpiryDate);
    } else if (extendMonths) {
      updatedExpiryDate = new Date(subscription.expiryDate);
      updatedExpiryDate.setMonth(updatedExpiryDate.getMonth() + Number(extendMonths));
    } else if (extendDays) {
      updatedExpiryDate = new Date(subscription.expiryDate);
      updatedExpiryDate.setDate(updatedExpiryDate.getDate() + Number(extendDays));
    } else {
      return NextResponse.json(
        { success: false, error: 'Please specify newExpiryDate, extendMonths, or extendDays' },
        { status: 400 }
      );
    }

    if (isNaN(updatedExpiryDate.getTime())) {
      return NextResponse.json({ success: false, error: 'Invalid expiry date calculation' }, { status: 400 });
    }

    // Append to audit log
    subscription.manualExtensionLogs.push({
      extendedBy: auth.user.id as any,
      extendedAt: new Date(),
      previousExpiryDate,
      newExpiryDate: updatedExpiryDate,
      reason: reason || 'Manual extension requested by student / granted by admin',
    });

    subscription.expiryDate = updatedExpiryDate;
    subscription.status = 'manually_extended';
    await subscription.save();

    return NextResponse.json({
      success: true,
      message: 'Subscription expiry extended successfully',
      subscription: {
        id: subscription._id,
        previousExpiryDate,
        newExpiryDate: subscription.expiryDate,
        status: subscription.status,
        lastLog: subscription.manualExtensionLogs[subscription.manualExtensionLogs.length - 1],
      },
    });
  } catch (error: any) {
    return NextResponse.json(
      { success: false, error: error.message || 'Server error extending subscription' },
      { status: 500 }
    );
  }
}
