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

export default defineEventHandler(async (event) => {
  console.log('[api/admin/migrate-member-ids.post] =========================');
  console.log('[api/admin/migrate-member-ids.post] POST /api/admin/migrate-member-ids - Migrate existing member IDs');
  console.log('[api/admin/migrate-member-ids.post] Request from:', getClientIP(event));
  
  try {
    // Validate session and require Admin privileges
    const sessionManager = createSessionManager();
    const cookieHeader = getCookie(event, 'monacousa-session') ? getHeader(event, 'cookie') : undefined;
    const session = sessionManager.getSession(cookieHeader);
    
    if (!session?.user) {
      throw createError({
        statusCode: 401,
        statusMessage: 'Authentication required'
      });
    }

    const userTier = session.user.tier;
    if (userTier !== 'admin') {
      throw createError({
        statusCode: 403,
        statusMessage: 'Administrator privileges required for member ID migration'
      });
    }

    console.log('[api/admin/migrate-member-ids.post] Authorized admin user:', session.user.email);

    // Find all members without member IDs
    console.log('[api/admin/migrate-member-ids.post] Finding members without member IDs...');
    const membersWithoutId = await findMembersWithoutMemberID();
    
    if (membersWithoutId.length === 0) {
      console.log('[api/admin/migrate-member-ids.post] No members found without member IDs');
      return {
        success: true,
        message: 'All members already have member IDs assigned',
        migrated: 0,
        total: 0
      };
    }

    console.log(`[api/admin/migrate-member-ids.post] Found ${membersWithoutId.length} members without member IDs`);

    const migrationResults = [];
    let successCount = 0;
    let errorCount = 0;

    // Migrate each member
    for (let i = 0; i < membersWithoutId.length; i++) {
      const member = membersWithoutId[i];
      console.log(`[api/admin/migrate-member-ids.post] Migrating member ${i + 1}/${membersWithoutId.length}: ${member.first_name} ${member.last_name} (ID: ${member.Id})`);
      
      try {
        // Generate unique member ID
        const memberID = await generateMemberID();
        console.log(`[api/admin/migrate-member-ids.post] Generated ID ${memberID} for member ${member.Id}`);
        
        // Update member with new member ID
        await updateMember(member.Id, { member_id: memberID });
        
        migrationResults.push({
          memberId: member.Id,
          memberName: `${member.first_name} ${member.last_name}`,
          generatedId: memberID,
          success: true
        });
        
        successCount++;
        console.log(`[api/admin/migrate-member-ids.post] ✅ Successfully migrated member ${member.Id} with ID ${memberID}`);
        
        // Add a small delay to avoid overwhelming the database
        if (i < membersWithoutId.length - 1) {
          await new Promise(resolve => setTimeout(resolve, 100));
        }
        
      } catch (error: any) {
        console.error(`[api/admin/migrate-member-ids.post] ❌ Failed to migrate member ${member.Id}:`, error);
        
        migrationResults.push({
          memberId: member.Id,
          memberName: `${member.first_name} ${member.last_name}`,
          generatedId: null,
          success: false,
          error: error.message || 'Unknown error'
        });
        
        errorCount++;
      }
    }

    console.log('[api/admin/migrate-member-ids.post] =========================');
    console.log('[api/admin/migrate-member-ids.post] Migration completed');
    console.log('[api/admin/migrate-member-ids.post] Total members processed:', membersWithoutId.length);
    console.log('[api/admin/migrate-member-ids.post] Successful migrations:', successCount);
    console.log('[api/admin/migrate-member-ids.post] Failed migrations:', errorCount);
    console.log('[api/admin/migrate-member-ids.post] =========================');

    return {
      success: errorCount === 0,
      message: `Migration completed. ${successCount} members successfully migrated, ${errorCount} errors.`,
      migrated: successCount,
      errors: errorCount,
      total: membersWithoutId.length,
      results: migrationResults
    };

  } catch (error: any) {
    console.error('[api/admin/migrate-member-ids.post] ❌ Migration failed:', error);
    handleNocoDbError(error, 'migrateMemberIDs', 'Member ID Migration');
  }
});
