import { verifyToken } from '../utils/auth.js'
import { readMembers } from '../utils/members.js'
import { readUsers, migrateUserRoles } from '../utils/auth.js'

export default defineEventHandler(async (event) => {
  try {
    const token = getCookie(event, 'auth_token')

    if (!token) {
      throw createError({
        statusCode: 401,
        message: 'Nicht authentifiziert.'
      })
    }

    const decoded = verifyToken(token)

    if (!decoded) {
      throw createError({
        statusCode: 401,
        message: 'Ungültiges Token.'
      })
    }

    // Get manual members and registered users
    const manualMembers = await readMembers()
    const registeredUsers = await readUsers()

    // Merge members: combine manual + registered, detect duplicates
    const mergedMembers = []
    const processedEmails = new Set()
    const processedNames = new Set()

    // First, add all manual members
    for (const member of manualMembers) {
      const normalizedEmail = member.email?.toLowerCase().trim() || ''
      const fullName = `${member.firstName || ''} ${member.lastName || ''}`.trim()
      const normalizedName = fullName.toLowerCase()

      mergedMembers.push({
        ...member,
        name: fullName, // Computed for display
        source: 'manual',
        editable: true,
        hasLogin: false
      })

      if (normalizedEmail) processedEmails.add(normalizedEmail)
      if (normalizedName) processedNames.add(normalizedName)
    }

    // Then add registered users (only active ones)
    for (const user of registeredUsers) {
      if (!user.active) continue

      const normalizedEmail = user.email?.toLowerCase().trim() || ''
      const normalizedName = user.name?.toLowerCase().trim() || ''

      // Check if this user matches an existing manual member
      let matchedManualIndex = -1

      // Try to match by email first
      if (normalizedEmail) {
        matchedManualIndex = mergedMembers.findIndex(
          m => m.source === 'manual' && m.email?.toLowerCase().trim() === normalizedEmail
        )
      }

      // If no email match, try name
      if (matchedManualIndex === -1 && normalizedName) {
        matchedManualIndex = mergedMembers.findIndex(
          m => m.source === 'manual' && m.name?.toLowerCase().trim() === normalizedName
        )
      }

      if (matchedManualIndex !== -1) {
        // Merge with existing manual member
        const migratedUser = migrateUserRoles({ ...user })
        const roles = Array.isArray(migratedUser.roles) ? migratedUser.roles : (migratedUser.role ? [migratedUser.role] : ['mitglied'])
        mergedMembers[matchedManualIndex] = {
          ...mergedMembers[matchedManualIndex],
          hasLogin: true,
          loginEmail: user.email,
          loginRoles: roles,
          loginRole: roles[0] || 'mitglied', // Rückwärtskompatibilität
          lastLogin: user.lastLogin,
          isMannschaftsspieler: user.isMannschaftsspieler === true || mergedMembers[matchedManualIndex].isMannschaftsspieler === true
        }
      } else {
        // Add as new member (from login system)
        const migratedUser = migrateUserRoles({ ...user })
        const roles = Array.isArray(migratedUser.roles) ? migratedUser.roles : (migratedUser.role ? [migratedUser.role] : ['mitglied'])
        mergedMembers.push({
          id: user.id,
          name: user.name,
          email: user.email,
          phone: user.phone || '',
          address: '',
          notes: `Rolle(n): ${roles.join(', ')}`,
          source: 'login',
          editable: false,
          hasLogin: true,
          loginEmail: user.email,
          loginRoles: roles,
          loginRole: roles[0] || 'mitglied', // Rückwärtskompatibilität
          lastLogin: user.lastLogin,
          isMannschaftsspieler: user.isMannschaftsspieler === true
        })
      }
    }

    // Sort by name
    mergedMembers.sort((a, b) => a.name.localeCompare(b.name))

    return {
      success: true,
      members: mergedMembers
    }
  } catch (error) {
    console.error('Fehler beim Abrufen der Mitgliederliste:', error)
    throw error
  }
})

