import { Hono } from 'hono'
import { timingSafeEqual } from '@zync/auth'
import { runLeadScoreRefresh } from '../../cron/lead-score-refresh'
import type { AppEnv } from '../../types'

export const leadScoreRefreshCron = new Hono<AppEnv>()

leadScoreRefreshCron.post('/', async (c) => {
  const secret = c.req.header('x-cron-secret') ?? ''
  const expected = c.env.CRON_SECRET
  if (!expected || expected.length < 16) return c.json({ error: 'Server misconfigured' }, 500)
  if (!timingSafeEqual(secret, expected)) return c.json({ error: 'Forbidden' }, 403)
  await runLeadScoreRefresh(c.env)
  return c.json({ ok: true }, 200)
})
