import { defineEventHandler, readBody, createError } from 'h3'
import { useStorage, useRuntimeConfig } from '#imports'
import { getUserSessionId } from 'nuxt-oidc-auth/runtime/server/utils/session.js'
import { decryptToken } from 'nuxt-oidc-auth/runtime/server/utils/security.js'

const ALLOWED_RESOURCES = [
  'https://orders.optovia.ru',
  'https://teams.optovia.ru',
  'https://kyc.optovia.ru',
  'https://exchange.optovia.ru'
]

export default defineEventHandler(async (event) => {
  const body = await readBody<{ resource: string; organization_id?: string }>(event)

  if (!body?.resource || !ALLOWED_RESOURCES.includes(body.resource)) {
    throw createError({ statusCode: 400, message: 'Invalid resource' })
  }

  // Официальная функция из nuxt-oidc-auth - правильный session ID
  const sessionId = await getUserSessionId(event)

  // Токены в persistent storage
  const persistentSession = await useStorage('oidc').getItem(sessionId)

  if (!persistentSession?.refreshToken) {
    throw createError({ statusCode: 401, message: 'No refresh token available' })
  }

  // Дешифровка (функция знает формат {encryptedToken, iv})
  const tokenKey = process.env.NUXT_OIDC_TOKEN_KEY!
  const refreshToken = await decryptToken(persistentSession.refreshToken, tokenKey)

  // Обмен на JWT для ресурса
  const config = useRuntimeConfig()
  const logtoConfig = config.oidc?.providers?.logto as {
    baseUrl: string
    clientId: string
    clientSecret: string
  }

  if (!logtoConfig?.baseUrl || !logtoConfig?.clientId || !logtoConfig?.clientSecret) {
    throw createError({ statusCode: 500, message: 'Logto configuration missing' })
  }

  const params: Record<string, string> = {
    grant_type: 'refresh_token',
    client_id: logtoConfig.clientId,
    client_secret: logtoConfig.clientSecret,
    refresh_token: refreshToken,
    resource: body.resource
  }

  // organization_id — это Logto Organization ID (не team.uuid!)
  if (body.organization_id) {
    params.organization_id = body.organization_id
  }

  const response = await fetch(`${logtoConfig.baseUrl}/oidc/token`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: new URLSearchParams(params)
  })

  if (!response.ok) {
    const error = await response.json().catch(() => ({}))
    throw createError({
      statusCode: response.status,
      message: error.error_description || error.error || 'Token exchange failed'
    })
  }

  const tokenResponse = await response.json()
  return {
    access_token: tokenResponse.access_token,
    token_type: tokenResponse.token_type,
    expires_in: tokenResponse.expires_in,
    resource: body.resource
  }
})
