/**
 * Trusted-device management endpoints — auth-2fa (Task 8).
 *
 * GET    /api/auth/trusted-devices      — list active trusted devices for current user+tenant
 * DELETE /api/auth/trusted-devices/:id  — revoke a specific device
 * DELETE /api/auth/trusted-devices      — revoke all devices for current user+tenant
 *
 * Requires: authMiddleware (session present)
 */
import { Hono } from 'hono'
import {
  createDb,
  listTrustedDevices,
  revokeTrustedDevice,
  revokeAllTrustedDevices,
} from '@zync/db/queries'
import type { UserId } from '@zync/types'
import type { AppEnv } from '../../types'

export const trustedDevicesRoute = new Hono<AppEnv>()

// GET /api/auth/trusted-devices
trustedDevicesRoute.get('/trusted-devices', async (c) => {
  const session = c.get('session')
  if (!session || session.type !== 'user' || !session.tid) {
    return c.json({ error: 'Unauthorized' }, 401)
  }

  const db = createDb(c.env)
  const devices = await listTrustedDevices(db, session.sub as UserId, session.tid)

  return c.json({
    devices: devices.map((d) => ({
      id: d.id,
      userAgent: d.userAgent,
      createdAt: d.createdAt.toISOString(),
      expiresAt: d.expiresAt.toISOString(),
    })),
  })
})

// DELETE /api/auth/trusted-devices/:id
trustedDevicesRoute.delete('/trusted-devices/:id', async (c) => {
  const session = c.get('session')
  if (!session || session.type !== 'user' || !session.tid) {
    return c.json({ error: 'Unauthorized' }, 401)
  }

  const id = c.req.param('id')
  const ip = c.req.header('CF-Connecting-IP') ?? 'unknown'

  const db = createDb(c.env)
  await revokeTrustedDevice(db, id, session.sub as UserId, session.tid, { actorIp: ip })

  return new Response(null, { status: 204 })
})

// DELETE /api/auth/trusted-devices
trustedDevicesRoute.delete('/trusted-devices', async (c) => {
  const session = c.get('session')
  if (!session || session.type !== 'user' || !session.tid) {
    return c.json({ error: 'Unauthorized' }, 401)
  }

  const ip = c.req.header('CF-Connecting-IP') ?? 'unknown'

  const db = createDb(c.env)
  await revokeAllTrustedDevices(db, session.sub as UserId, session.tid, { actorIp: ip })

  return new Response(null, { status: 204 })
})
