/**
 * GET /api/user/role-status
 *
 * Get user's active role and all available roles (for RoleSwitcher dropdown)
 *
 * Response:
 * {
 *   "activeRoleCode": "private",
 *   "roles": [
 *     {
 *       "code": "private",
 *       "displayName": "Privatperson",
 *       "description": "Private Nutzung",
 *       "hasRole": true,
 *       "requiresApproval": false
 *     },
 *     {
 *       "code": "educator",
 *       "displayName": "Pädagoge",
 *       "description": "Lehrkräfte und Schulen",
 *       "hasRole": false,
 *       "requiresApproval": true
 *     },
 *     ...
 *   ],
 *   "roleChangedByAdmin": false
 * }
 *
 * - Validates active role with TTL (re-checks DB every 5min)
 * - Returns ALL roles (approved + not-approved) for dropdown
 * - Includes "hasRole" flag to show which roles user actually has
 */

import { asc, eq } from 'drizzle-orm'
import { roles } from '../../database/schema'
import { getUserActiveRole } from '../../utils/role-session'
import { getUserApprovedRoleCodes } from '../../utils/roles'

export default defineEventHandler(async (event) => {
  const session = await requireUserSession(event)

  // Get active role (validates with TTL, auto-fallback if revoked)
  const activeRole = await getUserActiveRole(event)

  // Get user's approved role codes
  const approvedRoleCodes = await getUserApprovedRoleCodes(session.user.id)

  // Get ALL roles from database (for dropdown: show all, disabled if not approved)
  const db = useDatabase()
  const allRoles = await db.query.roles.findMany({
    where: eq(roles.active, true),
    orderBy: asc(roles.sortOrder),
  })

  // Map roles with "hasRole" status
  const rolesWithStatus = allRoles.map((role) => ({
    code: role.code,
    displayName: role.displayName,
    description: role.description,
    hasRole: approvedRoleCodes.includes(role.code),
    requiresApproval: role.requiresApproval,
  }))

  return {
    activeRoleCode: activeRole,
    roles: rolesWithStatus,
    roleChangedByAdmin: session.roleChangedByAdmin || false,
  }
})
