import { Hono } from 'hono'
import type { AuthEngine } from '@platform-modules/auth'
import { ACCESS_TOKEN_TTL_SECS } from '@platform-modules/auth/engine-custom'

import { fail, ok } from '../http.js'

type SessionRouteEnv = object

export interface SessionRouteDeps {
  authEngine: Pick<AuthEngine, 'signIn'>
}

type CredentialsBody = {
  email?: unknown
  password?: unknown
}

function validCredentials(body: CredentialsBody): body is { email: string; password: string } {
  return typeof body.email === 'string' && typeof body.password === 'string' && body.email.length > 0 && body.password.length > 0
}

export function createSessionRoute(deps: SessionRouteDeps) {
  const route = new Hono<SessionRouteEnv>()

  route.post('/session', async (context) => {
    const body = (await context.req.json()) as CredentialsBody
    if (!validCredentials(body)) {
      return fail('INVALID_REQUEST', 'Email and password are required', 400)
    }

    try {
      const result = await deps.authEngine.signIn({ email: body.email, password: body.password })
      context.header(
        'set-cookie',
        `access_token=${result.accessToken}; Max-Age=${ACCESS_TOKEN_TTL_SECS}; Path=/; HttpOnly; Secure; SameSite=Lax`,
      )
      return ok({ userId: result.principal.userId, roles: result.principal.roles })
    } catch {
      return fail('UNAUTHORIZED', 'Invalid email or password', 401)
    }
  })

  return route
}
