// Server-only helpers for customer API keys and the public `/api/v1` routes.
import { and, eq, isNull } from 'drizzle-orm'
import { db } from '../../db/index.js'
import { accounts, apiKeys } from '../../db/schema.js'
import { SendError } from './messaging.server'

const KEY_PREFIX = 'akc_live_'

async function sha256(value: string) {
  const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value))
  return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('')
}

// Returns the full key (shown to the customer once) and what we store.
export async function generateApiKey() {
  const bytes = crypto.getRandomValues(new Uint8Array(24))
  const secret = btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
  const key = `${KEY_PREFIX}${secret}`
  return { key, prefix: key.slice(0, KEY_PREFIX.length + 4), keyHash: await sha256(key) }
}

export function apiJson(body: unknown, status = 200) {
  return Response.json(body, { status, headers: { 'Cache-Control': 'no-store' } })
}

export function apiError(code: string, message: string, status: number) {
  return apiJson({ ok: false, error: { code, message } }, status)
}

// Reads the key from `Authorization: Bearer …` or `X-API-Key` and returns the
// owning account, or null when the key is missing, unknown or revoked.
export async function authenticateApiKey(request: Request) {
  const header = request.headers.get('authorization')
  const key = (header?.match(/^Bearer\s+(.+)$/i)?.[1] ?? request.headers.get('x-api-key') ?? '').trim()
  if (!key.startsWith(KEY_PREFIX) || key.length > 100) return null

  const [row] = await db
    .select({ keyId: apiKeys.id, userId: accounts.userId, credits: accounts.credits, email: accounts.email })
    .from(apiKeys)
    .innerJoin(accounts, eq(accounts.userId, apiKeys.userId))
    .where(and(eq(apiKeys.keyHash, await sha256(key)), isNull(apiKeys.revokedAt)))
  if (!row) return null

  await db.update(apiKeys).set({ lastUsedAt: new Date() }).where(eq(apiKeys.id, row.keyId))
  return row
}

// Wraps an API handler with key authentication and consistent error output.
export function withApiKey(
  handler: (ctx: { request: Request; account: NonNullable<Awaited<ReturnType<typeof authenticateApiKey>>>; params: Record<string, string> }) => Promise<Response>,
) {
  return async ({ request, params }: { request: Request; params?: Record<string, string> }) => {
    try {
      const account = await authenticateApiKey(request)
      if (!account) {
        return apiError('unauthorized', 'Missing or invalid API key. Send it as "Authorization: Bearer <key>".', 401)
      }
      return await handler({ request, account, params: params ?? {} })
    } catch (error) {
      if (error instanceof SendError) return apiError(error.code, error.message, error.status)
      console.error('Public API request failed', error)
      return apiError('server_error', 'Something went wrong on our side. Please try again.', 500)
    }
  }
}
