import { sendEmail } from '../../utils/email'
import { ApiErrors, createSuccessResponse } from '../../utils/errors'

interface LoginNotificationRequest {
  user: {
    name: string
    email: string
    city?: string
    country?: string
  }
}

interface LoginNotificationResponse {
  sent: boolean
}

export default defineEventHandler(async (event) => {
  try {
    // Get user data from the request body
    const body = await readBody<LoginNotificationRequest>(event)
    const { user } = body

    if (!user?.name || !user?.email) {
      throw ApiErrors.validationError('Missing required user information')
    }

    const htmlTemplate = await renderEmailComponent('login-notification', {
      userName: user.name,
      city: user.city,
      country: user.country
    })
    const htmlTemplateAdmin = await renderEmailComponent('login-notification-admin', {
      userName: user.name,
      city: user.city,
      country: user.country
    })

    const config = useRuntimeConfig()
    if (!config.mockEmail) {
      await sendEmail({
        to: user.email,
        subject: `Login to ${config.public.appName || 'the app'} from a new location`,
        html: htmlTemplate
      })
      if (user.email !== config.fromEmail) {
        await sendEmail({
          to: config.fromEmail,
          subject: `${user.name} logged in to ${config.public.appName || 'the app'}`,
          html: htmlTemplateAdmin
        })
      }
    }

    return createSuccessResponse<LoginNotificationResponse>({ sent: true }, 'Login notification sent')
  } catch (error) {
    // Don't throw error as this is not critical - just log and return failure
    console.error('Failed to send login notification email:', error)
    return createSuccessResponse<LoginNotificationResponse>({ sent: false })
  }
})
