import { getMemberById, handleNocoDbError } from '~/server/utils/nocodb';

export default defineEventHandler(async (event) => {
  const id = getRouterParam(event, 'id');
  
  console.log('[api/members/[id].get] =========================');
  console.log('[api/members/[id].get] GET /api/members/' + id);
  console.log('[api/members/[id].get] Request from:', getClientIP(event));
  
  if (!id) {
    throw createError({
      statusCode: 400,
      statusMessage: 'Member ID is required'
    });
  }

  try {
    const member = await getMemberById(id);
    
    // Add computed fields
    const processedMember = {
      ...member,
      FullName: `${member.first_name || ''} ${member.last_name || ''}`.trim(),
      FormattedPhone: formatPhoneNumber(member.phone)
    };

    console.log('[api/members/[id].get] ✅ Successfully retrieved member:', id);

    return {
      success: true,
      data: processedMember
    };

  } catch (error: any) {
    console.error('[api/members/[id].get] ❌ Error fetching member:', error);
    handleNocoDbError(error, 'getMemberById', 'Member');
  }
});

function formatPhoneNumber(phone: string): string {
  if (!phone) return '';
  const cleaned = phone.replace(/\D/g, '');
  if (cleaned.length === 10) {
    return `(${cleaned.substring(0, 3)}) ${cleaned.substring(3, 6)}-${cleaned.substring(6)}`;
  } else if (cleaned.length === 11 && cleaned.startsWith('1')) {
    return `+1 (${cleaned.substring(1, 4)}) ${cleaned.substring(4, 7)}-${cleaned.substring(7)}`;
  }
  return phone;
}
