import type { OAuth2Tokens } from 'arctic'
import { decodeJwt } from 'jose'
import { Authenticator } from 'remix-auth'
import { CodeChallengeMethod, OAuth2Strategy } from 'remix-auth-oauth2'

export type User = {
  sub: string
  email: string
  name: string
  scope: string
  email_verified: boolean
  accessToken: string
  refreshToken: string
}

export function createAuth(env) {
  const authenticator = new Authenticator()
  const strategy = new OAuth2Strategy(
    {
      clientId: env.CLIENT_ID,
      clientSecret: env.CLIENT_SECRET,
      redirectURI: env.REDIRECT_URI,
      authorizationEndpoint: `${env.ISSUER_URL}/authorize`,
      tokenEndpoint: `${env.ISSUER_URL}/token`,
      tokenRevocationEndpoint: `${env.ISSUER_URL}/revoke`,
      scopes: env.SCOPE.split(' '),
      codeChallengeMethod: CodeChallengeMethod.S256
    },
    async ({ tokens }: { tokens: OAuth2Tokens }) => {
      const user = decodeJwt(tokens.idToken())

      return {
        ...user,
        accessToken: tokens.accessToken(),
        refreshToken: tokens.hasRefreshToken() ? tokens.refreshToken() : null
      }
    }
  )

  authenticator.use(strategy, 'oidc')

  return authenticator
}
