import { getMembers, updateMember } from '~/server/utils/nocodb';
import { findMembersWithoutMemberID, generateMemberID, extractMemberIDNumber } from '~/server/utils/member-id';
import type { Member } from '~/utils/types';

export default defineEventHandler(async (event) => {
  console.log('[api/admin/assign-member-ids.post] =========================');
  console.log('[api/admin/assign-member-ids.post] POST /api/admin/assign-member-ids - Assign member IDs to existing members');

  try {
    // Check if user is admin
    const sessionManager = createSessionManager();
    const cookieHeader = getHeader(event, 'cookie');
    const session = sessionManager.getSession(cookieHeader);
    
    if (!session || session.user.tier !== 'admin') {
      throw createError({
        statusCode: 403,
        statusMessage: 'Admin access required'
      });
    }

    // Get all members and find those without member IDs
    const allMembersResult = await getMembers();
    const allMembers = allMembersResult.list || [];
    console.log(`[api/admin/assign-member-ids.post] Found ${allMembers.length} total members`);

    // Find members without member_id
    const membersWithoutIds = await findMembersWithoutMemberID();
    console.log(`[api/admin/assign-member-ids.post] Found ${membersWithoutIds.length} members without IDs`);

    if (membersWithoutIds.length === 0) {
      return {
        success: true,
        message: 'All members already have member IDs assigned',
        data: {
          totalMembers: allMembers.length,
          membersUpdated: 0
        }
      };
    }

    // Get the highest existing member ID number to continue sequence
    const existingMemberIds = allMembers
      .filter((member: Member) => member.member_id)
      .map((member: Member) => extractMemberIDNumber(member.member_id!))
      .filter(num => num !== null) as number[];
    
    // Start from next available number, or 1 if no existing IDs
    let nextIdNumber = existingMemberIds.length > 0 ? Math.max(...existingMemberIds) + 1 : 1;
    console.log(`[api/admin/assign-member-ids.post] Starting with member ID number: ${nextIdNumber}`);

    // Assign IDs to members without them
    const updatedMembers = [];
    
    for (const member of membersWithoutIds) {
      // Use 4-digit padding for member IDs (MUSA-0001, MUSA-0002, etc.)
      const memberId = `MUSA-${nextIdNumber.toString().padStart(4, '0')}`;
      
      try {
        await updateMember(member.Id, {
          member_id: memberId
        });
        
        updatedMembers.push({
          id: member.Id,
          name: `${member.first_name || ''} ${member.last_name || ''}`.trim() || 'Unknown',
          email: member.email || 'No email',
          memberId
        });
        
        console.log(`[api/admin/assign-member-ids.post] Assigned ${memberId} to ${member.first_name} ${member.last_name}`);
        nextIdNumber++;
        
      } catch (updateError: any) {
        console.error(`[api/admin/assign-member-ids.post] Failed to assign ID to member ${member.Id}:`, updateError);
        // Continue with next member rather than failing the entire operation
      }
    }

    console.log(`[api/admin/assign-member-ids.post] ✅ Successfully assigned IDs to ${updatedMembers.length} members`);

    return {
      success: true,
      message: `Successfully assigned member IDs to ${updatedMembers.length} members`,
      data: {
        totalMembers: allMembers.length,
        membersUpdated: updatedMembers.length,
        updatedMembers: updatedMembers.slice(0, 10), // Return first 10 for display
        startingId: updatedMembers.length > 0 ? `MUSA-${(nextIdNumber - updatedMembers.length).toString().padStart(4, '0')}` : null,
        endingId: updatedMembers.length > 0 ? updatedMembers[updatedMembers.length - 1].memberId : null
      }
    };

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