import { defineEventHandler, parseCookies } from 'h3'
import { handleApiError, ApiErrors, createSuccessResponse } from '../../utils/errors'

interface TokenResponse {
  token: string
}

export default defineEventHandler((event) => {
  try {
    const cookies = parseCookies(event)
    const keys = Object.keys(cookies)

    // Look for a plausible Better Auth session cookie key
    const key = keys.find(k => k.includes('session_token'))
      || keys.find(k => k.includes('better') && k.includes('session'))
      || keys.find(k => k.includes('session'))

    const cookieValue = key ? cookies[key] : ''

    if (!cookieValue) {
      throw ApiErrors.unauthorized('No session token cookie found')
    }

    // Unsign: Better Auth cookies may be signed as `<token>.<signature>`
    const rawToken = cookieValue.split('.')[0] || cookieValue

    return createSuccessResponse<TokenResponse>({ token: rawToken })
  } catch (error) {
    throw handleApiError(error)
  }
})
