import {
  getAuthConfig,
  getOidcConfig,
  getOidcRedirectUri,
  createOidcParams,
  getCodeChallenge,
  buildAuthorizeUrl,
} from '../../../utils/oidc.js'

const SCOPES = process.env.OIDC_SCOPES || 'openid profile email'

export default defineEventHandler(async (event) => {
  const { oidc: { enabled } } = getAuthConfig()
  if (!enabled) throw createError({ statusCode: 400, message: 'OIDC not enabled' })

  const config = await getOidcConfig()
  if (!config) throw createError({ statusCode: 500, message: 'OIDC not configured' })

  const redirectUri = getOidcRedirectUri()
  const { state, nonce, codeVerifier } = createOidcParams()
  const codeChallenge = await getCodeChallenge(codeVerifier)

  const params = {
    redirect_uri: redirectUri,
    scope: SCOPES,
    state,
    nonce,
    code_challenge: codeChallenge,
    code_challenge_method: 'S256',
  }

  const url = buildAuthorizeUrl(config, params)
  setCookie(event, 'oidc_state', JSON.stringify({ state, nonce, codeVerifier }), {
    httpOnly: true,
    sameSite: 'lax',
    path: '/',
    maxAge: 600,
    secure: process.env.NODE_ENV === 'production',
  })
  return sendRedirect(event, url.href, 302)
})
