import { updateUserProfile } from '../../database/queries/users.ts'
import { handleApiError, ApiErrors, createSuccessResponse } from '../../utils/errors.ts'
import { useDB, eq } from '../../utils/database.ts'
import { session as sessionTable } from '../../database/schema/auth.ts'

interface UpdateUserRequest {
  name: string
  image?: string
  preferredLanguage?: string
  timezone?: string
}

interface UserProfileResponse {
  id: string
  name: string
  email: string
  image: string | null
  emailVerified: boolean
  preferredLanguage: string | null
  timezone: string | null
  updatedAt: Date
}

export default defineEventHandler(async (event) => {
  // Only allow PUT method
  assertMethod(event, 'PUT')

  try {
    // Get the session to verify user is authenticated using Better Auth server API
    const session = await requireUserSession(event)

    // Parse request body
    const body = await readBody(event) as UpdateUserRequest

    // Validate required fields
    if (!body.name) {
      throw ApiErrors.validationError('Name is required')
    }

    const updated = await updateUserProfile(session.user.id, {
      name: body.name,
      image: body.image ?? null,
      preferredLanguage: body.preferredLanguage,
      timezone: body.timezone
    })

    if (!updated) {
      throw ApiErrors.notFound('User not found')
    }

    // Force Better Auth to refresh user data by updating the session's updatedAt timestamp
    // Better Auth caches session data (including user) for 5 minutes based on cookieCache.maxAge
    // Updating the session's updatedAt to a future time forces Better Auth to bypass its cache
    // We update ALL sessions for the user to ensure cache invalidation works across all devices
    const db = useDB()
    // Set updatedAt to a future time to ensure Better Auth bypasses its cache
    const futureTime = new Date(Date.now() + 60000) // 1 minute in the future
    await db
      .update(sessionTable)
      .set({ updatedAt: futureTime })
      .where(eq(sessionTable.userId, session.user.id))

    // Return standardized ApiResponse format
    return createSuccessResponse<UserProfileResponse>({
      id: updated.id,
      name: updated.name,
      email: updated.email,
      image: updated.image,
      emailVerified: updated.emailVerified,
      preferredLanguage: updated.preferredLanguage,
      timezone: updated.timezone,
      updatedAt: updated.updatedAt
    }, 'Profile updated successfully')
  } catch (error) {
    throw handleApiError(error)
  }
})
