import { updateUserPreferences } from '../../database/queries/users'
import { handleApiError, ApiErrors, createSuccessResponse } from '../../utils/errors'

interface UpdatePreferencesRequest {
  preferredLanguage?: string
  timezone?: string
}

interface PreferencesResponse {
  preferredLanguage: string | null
  timezone: string | null
}

export default defineEventHandler(async (event) => {
  try {
    // Get the session to verify user is authenticated
    const session = await requireUserSession(event)

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

    // Validate language if provided (should be a valid locale code)
    if (body.preferredLanguage !== undefined && body.preferredLanguage !== null) {
      // Basic validation - should be a short string like 'en', 'nl', 'fr', etc.
      if (typeof body.preferredLanguage !== 'string' || body.preferredLanguage.length > 10) {
        throw ApiErrors.validationError('Invalid language code')
      }
    }

    // Validate timezone if provided (should be a valid IANA timezone)
    if (body.timezone !== undefined && body.timezone !== null) {
      if (typeof body.timezone !== 'string' || body.timezone.length > 50) {
        throw ApiErrors.validationError('Invalid timezone')
      }
    }

    const updated = await updateUserPreferences(session.user.id, {
      preferredLanguage: body.preferredLanguage,
      timezone: body.timezone
    })

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

    return createSuccessResponse<PreferencesResponse>({
      preferredLanguage: updated.preferredLanguage,
      timezone: updated.timezone
    }, 'Preferences updated successfully')
  } catch (error) {
    throw handleApiError(error)
  }
})
