// server/api/admin/generate-member-ids.post.ts
export default defineEventHandler(async (event) => {
  try {
    const body = await readBody(event).catch(() => ({}));
    const { forceRegenerate = false } = body;

    const { getMembers, updateMember } = await import('~/server/utils/nocodb');
    const { generateUniqueMemberId } = await import('~/server/utils/member-id');

    console.log('[api/admin/generate-member-ids.post] Starting member ID generation...');

    // Get all members
    const membersResponse = await getMembers();
    const members = membersResponse?.list || [];

    if (members.length === 0) {
      return {
        success: true,
        message: 'No members found to process',
        stats: {
          total: 0,
          generated: 0,
          skipped: 0,
          failed: 0
        }
      };
    }

    // Filter members that need IDs (unless force regenerate)
    const membersToProcess = forceRegenerate 
      ? members 
      : members.filter((member: any) => !member.member_id || member.member_id.trim() === '');

    console.log(`[api/admin/generate-member-ids.post] Found ${membersToProcess.length} members to process (out of ${members.length} total)`);

    const results = {
      total: members.length,
      generated: 0,
      skipped: members.length - membersToProcess.length,
      failed: 0,
      errors: [] as any[]
    };

    // Process each member
    for (const member of membersToProcess) {
      try {
        // Generate unique member ID
        const memberID = await generateUniqueMemberId();
        
        console.log(`[api/admin/generate-member-ids.post] Generated ID ${memberID} for ${member.first_name} ${member.last_name} (ID: ${member.Id})`);

        // Update the member with the new ID
        await updateMember(member.Id, { 
          member_id: memberID 
        });

        results.generated++;

        console.log(`[api/admin/generate-member-ids.post] ✅ Successfully assigned ID ${memberID} to member ${member.Id}`);

      } catch (error: any) {
        console.error(`[api/admin/generate-member-ids.post] ❌ Failed to generate ID for member ${member.Id}:`, error);
        results.failed++;
        results.errors.push({
          memberId: member.Id,
          name: `${member.first_name} ${member.last_name}`,
          error: error.message || 'Unknown error'
        });
      }
    }

    // Calculate and update payment_due_date for all members with membership_date_paid
    console.log('[api/admin/generate-member-ids.post] Updating payment due dates for paid members...');
    
    let duesDatesFixed = 0;
    for (const member of members) {
      if (member.membership_date_paid && !member.payment_due_date) {
        try {
          const paymentDate = new Date(member.membership_date_paid);
          const dueDate = new Date(paymentDate);
          dueDate.setFullYear(dueDate.getFullYear() + 1);
          
          await updateMember(member.Id, {
            payment_due_date: dueDate.toISOString().split('T')[0]
          });
          
          duesDatesFixed++;
          console.log(`[api/admin/generate-member-ids.post] Fixed payment_due_date for member ${member.Id}`);
        } catch (error) {
          console.error(`[api/admin/generate-member-ids.post] Failed to fix payment_due_date for member ${member.Id}:`, error);
        }
      }
    }

    const message = `Member ID generation complete!\n` +
      `Generated: ${results.generated} IDs\n` +
      `Skipped: ${results.skipped} (already have IDs)\n` +
      `Failed: ${results.failed}\n` +
      `Payment Due Dates Fixed: ${duesDatesFixed}`;

    console.log(`[api/admin/generate-member-ids.post] ${message}`);

    return {
      success: results.failed === 0,
      message,
      stats: {
        ...results,
        duesDatesFixed
      }
    };

  } catch (error: any) {
    console.error('[api/admin/generate-member-ids.post] Error:', error);
    throw createError({
      statusCode: error.statusCode || 500,
      statusMessage: error.message || 'Failed to generate member IDs'
    });
  }
});