// server/api/auth/me.get.ts

/**
 * GET /api/auth/me
 *
 * Get current authenticated user
 *
 * Response:
 * {
 *   "id": "uuid",
 *   "experimentaId": "cidaas-sub",
 *   "email": "user@example.com",
 *   "firstName": "Max",
 *   "lastName": "Mustermann",
 *   ...
 * }
 *
 * Returns 401 if not authenticated
 */

import { eq } from 'drizzle-orm'
import { users } from '../../database/schema'

export default defineEventHandler(async (event) => {
  // 1. Require authentication (throws 401 if not logged in)
  const { user: sessionUser } = await requireUserSession(event)

  // 2. Fetch fresh user data from database
  const db = useDatabase()
  const user = await db.query.users.findFirst({
    where: eq(users.id, sessionUser.id),
  })

  if (!user) {
    throw createError({
      statusCode: 404,
      statusMessage: 'User not found',
    })
  }

  // 3. Return user profile (exclude sensitive fields if any)
  return {
    id: user.id,
    experimentaId: user.experimentaId,
    email: user.email,
    firstName: user.firstName,
    lastName: user.lastName,
    phone: user.phone,

    // Billing address
    salutation: user.salutation,
    dateOfBirth: user.dateOfBirth,
    street: user.street,
    postCode: user.postCode,
    city: user.city,
    countryCode: user.countryCode,

    createdAt: user.createdAt,
    updatedAt: user.updatedAt,
  }
})
