import {Hono} from 'hono'
import {z} from 'zod'

import {type GuardedVars} from '../auth/middleware'
import {extractLimiter} from '../lib/rate-limit'
import {validate} from '../lib/validate'
import {
  extractLinkDrafts,
  extractScreengrabDrafts,
} from '../services/extract'

const RequestSchema = z.union([
  z.object({image: z.string().min(1), mimeType: z.string().min(1)}),
  z.object({url: z.url().max(2048)}),
])

const extract = new Hono<{Variables: GuardedVars}>().post(
  '/',
  extractLimiter,
  validate('json', RequestSchema, 'missing_input'),
  async (c) => {
    const user = c.get('user')
    const body = c.req.valid('json')

    const drafts =
      'url' in body
        ? await extractLinkDrafts(user.id, body.url)
        : await extractScreengrabDrafts(
            user.id,
            body,
            c.req.header('X-LLM-Key'),
          )

    return c.json({drafts})
  },
)

export default extract
