import { getUserById } from '../../../database/queries/users'
import { setCookie } from 'h3'
import { requireSuperAdmin } from '../../../utils/auth'
import { handleApiError, ApiErrors, createSuccessResponse } from '../../../utils/errors'

interface ImpersonateRequest {
  userId: string
}

interface ImpersonateResponse {
  userId: string
  impersonating: string
}

export default defineEventHandler(async (event) => {
  try {
    // Require super admin access
    await requireSuperAdmin(event)

    const body = await readBody(event) as ImpersonateRequest
    const { userId } = body

    if (!userId) {
      throw ApiErrors.validationError('User ID is required')
    }

    const userToImpersonate = await getUserById(userId)
    if (!userToImpersonate) {
      throw ApiErrors.notFound('User not found')
    }

    // Mark impersonation via cookie; session resolution will apply this
    setCookie(event, 'impersonateUserId', userToImpersonate.id, {
      httpOnly: true,
      sameSite: 'lax',
      path: '/',
      maxAge: 60 * 60 // 1 hour
    })

    return createSuccessResponse<ImpersonateResponse>({
      userId: userToImpersonate.id,
      impersonating: userToImpersonate.email || userToImpersonate.name || userId
    }, 'Impersonation started')
  } catch (error) {
    throw handleApiError(error)
  }
})
