import type {User} from '@crumbs/core/db'
import {createMiddleware} from 'hono/factory'

import {resolveSession} from './session'

export type AuthVars = {
  user: User | null
  sessionToken: string | null
}

export type GuardedVars = {user: User}

const readBearer = (header: string | undefined): string | null => {
  if (!header) return null
  const [scheme, token] = header.split(' ')
  if (scheme?.toLowerCase() !== 'bearer' || !token) return null
  return token
}

export const auth = createMiddleware<{Variables: AuthVars}>(
  async (c, next) => {
    const token = readBearer(c.req.header('Authorization'))
    const session = token ? await resolveSession(token) : null
    c.set('user', session?.user ?? null)
    c.set('sessionToken', token)
    await next()
  },
)

export const requireUser = createMiddleware<{
  Variables: {user: User}
}>(async (c, next) => {
  if (!c.get('user')) return c.json({error: 'unauthorized'}, 401)
  await next()
})
