// server/api/members/[id]/mark-dues-paid.post.ts
export default defineEventHandler(async (event) => {
  try {
    const memberId = getRouterParam(event, 'id');
    
    if (!memberId) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Member ID is required'
      });
    }

    // Get request body for custom payment date
    const body = await readBody(event).catch(() => ({}));
    const customPaymentDate = body.paymentDate;

    const { updateMember, getMemberById } = await import('~/server/utils/nocodb');

    // Get current member data
    const currentMember = await getMemberById(memberId);
    
    if (!currentMember) {
      throw createError({
        statusCode: 404,
        statusMessage: 'Member not found'
      });
    }

    // Determine payment date - use custom date if provided, otherwise today
    let paymentDate: string;
    if (customPaymentDate) {
      try {
        // Validate the custom date
        const parsedDate = new Date(customPaymentDate);
        if (isNaN(parsedDate.getTime())) {
          throw new Error('Invalid date format');
        }
        paymentDate = parsedDate.toISOString().split('T')[0]; // YYYY-MM-DD format
      } catch (error) {
        throw createError({
          statusCode: 400,
          statusMessage: 'Invalid payment date provided. Please use YYYY-MM-DD format.'
        });
      }
    } else {
      // Default to today if no custom date provided
      paymentDate = new Date().toISOString().split('T')[0];
    }

    // Prepare update data
    const updateData = {
      current_year_dues_paid: 'true',
      membership_date_paid: paymentDate,
      membership_status: 'Active', // Ensure member is marked as active when dues are paid
      payment_due_date: undefined // Clear the due date since it's now paid
    };

    // Update the member
    const updatedMember = await updateMember(memberId, updateData);

    console.log(`[API] Successfully marked dues as paid for member ${memberId} with payment date: ${paymentDate}`);

    return {
      success: true,
      data: updatedMember,
      message: `Dues marked as paid for ${updatedMember.first_name} ${updatedMember.last_name} (Payment Date: ${paymentDate})`
    };

  } catch (error: any) {
    console.error('[API] Error marking dues as paid:', error);
    
    throw createError({
      statusCode: error.statusCode || 500,
      statusMessage: error.message || 'Failed to mark dues as paid'
    });
  }
});
