/**
 * Stale timer cleanup cron — time-management.
 *
 * POST /api/cron/time-cleanup
 *
 * Guarded by CRON_SECRET (timing-safe comparison via @zync/auth#timingSafeEqual).
 * Finds entries where stopped_at IS NULL AND started_at < now() - interval '2 hours'.
 * Auto-stops them with source='auto', fires timer.stopped webhook for each.
 *
 * Scheduled: hourly (see wrangler.toml manifest.wrangler entry).
 */
import { Hono } from 'hono'
import { timingSafeEqual } from '@zync/auth'
import { createDb, createNotification, evaluateBudgetAlert } from '@zync/db/queries'
import { findStaleRunningEntries, stopStaleEntry } from '@zync/time'
import { enqueueTimerWebhook } from '../../lib/time-webhooks'
import type { AppEnv } from '../../types'

export const timeCleanupCronRoute = new Hono<AppEnv>()

timeCleanupCronRoute.post('/', async (c) => {
  // Timing-safe secret check — never use ===
  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: 'Unauthorized' }, 401)
  }

  const db = createDb(c.env)

  const staleEntries = await findStaleRunningEntries(db)
  let stopped = 0

  for (const entry of staleEntries) {
    try {
      const stopped_entry = await stopStaleEntry(db, entry)
      stopped++

      await enqueueTimerWebhook(c.env, entry.tenantId, {
        event: 'timer.stopped',
        payload: {
          entryId: stopped_entry.id,
          userId: stopped_entry.userId,
          taskId: stopped_entry.taskId,
          projectId: stopped_entry.projectId,
          startedAt: stopped_entry.startedAt,
          stoppedAt: stopped_entry.stoppedAt!,
          durationSeconds: stopped_entry.durationSeconds,
        },
      })
      if (stopped_entry.projectId) {
        c.executionCtx.waitUntil(
          evaluateBudgetAlert(db, entry.tenantId, stopped_entry.projectId, { createNotif: createNotification }),
        )
      }
    } catch (err) {
      console.error('[time-cleanup] Failed to stop stale entry', entry.id, err)
    }
  }

  return c.json({ stopped, ok: true }, 200)
})
