// Update member's email address
import Member from '../../models/member.js'
import { connectDB } from '../../utils/mongoose.js'
import { requireAuth } from '../../utils/auth.js'

const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

export default defineEventHandler(async (event) => {
  try {
    const member = await requireAuth(event)
    await connectDB()

    const body = await readBody(event)
    const newEmail = (body?.email ?? '').trim().toLowerCase()

    if (!newEmail) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Email address is required',
      })
    }

    if (!EMAIL_REGEX.test(newEmail)) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Invalid email address format',
      })
    }

    const oldEmail = member.email.trim().toLowerCase()

    if (newEmail === oldEmail) {
      throw createError({
        statusCode: 400,
        statusMessage: 'New email address must be different from your current email',
      })
    }

    const existing = await Member.findOne({
      email: newEmail,
      _id: { $ne: member._id },
    })

    if (existing) {
      throw createError({
        statusCode: 409,
        statusMessage: 'This email address is already in use by another account',
      })
    }

    await Member.findByIdAndUpdate(
      member._id,
      {
        $set: { email: newEmail },
        $push: {
          emailHistory: {
            email: oldEmail,
            changedAt: new Date(),
          },
        },
      },
      { runValidators: false }
    )

    logActivity(member._id, 'email_changed', { previousEmail: oldEmail })

    return {
      success: true,
      email: newEmail,
    }
  } catch (error) {
    if (error.statusCode) throw error
    console.error('Error updating email:', error)
    throw createError({
      statusCode: 500,
      statusMessage: 'An unexpected error occurred',
    })
  }
})
