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
        }
      };
    }

    // Use the same generation method as new members to maintain consistency
    // Generate unique 6-digit member IDs for consistency with existing format
    const updatedMembers = [];
    
    for (const member of membersWithoutIds) {
      try {
        // Use the same generateMemberID function to ensure consistency
        const memberId = await generateMemberID();
        
        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}`);
        
      } 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
        firstAssignedId: updatedMembers.length > 0 ? updatedMembers[0].memberId : null,
        lastAssignedId: 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'
    });
  }
});
