/**
 * Public tenant-logo proxy — unauthenticated, strict-guarded.
 *
 * GET /api/public/tenant-logo/:tid/:file
 *
 * Serves ONLY tenant brand logos from the shared zync-storage bucket
 * (key `tenants/{uuid}/logo.{png|jpg}`). The bucket also holds sensitive
 * tax/expense/accounting files, so the key is validated to fully match the
 * logo shape and nothing else. Content-Type is forced from the validated
 * extension (content-type-confusion defense), never trusted from R2 metadata.
 *
 * Public by design: logos render in customer-facing PDFs/invoices.
 */
import { Hono } from 'hono'
import type { Env } from '../../env'

const TID_RE = /^[0-9a-fA-F-]{36}$/
const FILE_RE = /^logo\.(png|jpg)$/
const FULL_KEY_RE = /^tenants\/[0-9a-fA-F-]{36}\/logo\.(png|jpg)$/

const EXT_CONTENT_TYPE: Record<'png' | 'jpg', string> = {
  png: 'image/png',
  jpg: 'image/jpeg',
}

export const tenantLogoPublicRoute = new Hono<{ Bindings: Env }>()

tenantLogoPublicRoute.get('/:tid/:file', async (c) => {
  const tid = c.req.param('tid')
  const file = c.req.param('file')

  if (!TID_RE.test(tid)) {
    return c.json({ error: 'Forbidden' }, 403)
  }
  const fileMatch = file.match(FILE_RE)
  if (!fileMatch) {
    return c.json({ error: 'Forbidden' }, 403)
  }

  const key = `tenants/${tid}/${file}`
  if (
    key.includes('..') ||
    key.includes('\\') ||
    key.startsWith('/') ||
    !FULL_KEY_RE.test(key)
  ) {
    return c.json({ error: 'Forbidden' }, 403)
  }

  const obj = await c.env.STORAGE.get(key)
  if (!obj) {
    return c.json({ error: 'Not found' }, 404)
  }

  const ext = fileMatch[1] as 'png' | 'jpg'
  const headers = new Headers()
  headers.set('Content-Type', EXT_CONTENT_TYPE[ext])
  headers.set('X-Content-Type-Options', 'nosniff')
  headers.set('Cache-Control', 'public, max-age=300, stale-while-revalidate=60')
  if (obj.httpEtag) {
    headers.set('etag', obj.httpEtag)
  }

  return new Response(obj.body, { headers })
})
