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

import { getDb } from '@/shared/db';
import { getSendRateConfig, setSendRateConfig } from '@/entities/send-queue';

const updateSchema = z.object({
  maxSends: z.number().int().min(1).max(1000),
  windowSeconds: z.number().int().min(1).max(86_400),
  autoQueue: z.boolean().default(true),
});

/**
 * Admin control for the global outbound send-rate cap.
 *   GET /admin/send-rate-limit       → current { maxSends, windowSeconds, updatedAt }
 *   PUT /admin/send-rate-limit {…}    → update and return the new config
 */
export const sendRateLimitAdminRouter = new Hono()
  .get('/', async (c) => {
    try {
      const cfg = await getSendRateConfig(getDb());
      return c.json({ success: true, data: cfg });
    } catch (err) {
      return c.json(
        {
          success: false,
          error: {
            code: 'send_rate_limit_error',
            message: err instanceof Error ? err.message : 'failed to read send-rate config',
          },
        },
        500,
      );
    }
  })
  .put('/', async (c) => {
    try {
      const { maxSends, windowSeconds, autoQueue } = updateSchema.parse(await c.req.json());
      const cfg = await setSendRateConfig(getDb(), maxSends, windowSeconds, autoQueue);
      return c.json({ success: true, data: cfg });
    } catch (err) {
      const isValidation = err instanceof z.ZodError;
      return c.json(
        {
          success: false,
          error: {
            code: isValidation ? 'invalid_request' : 'send_rate_limit_error',
            message: err instanceof Error ? err.message : 'failed to update send-rate config',
          },
        },
        isValidation ? 400 : 500,
      );
    }
  });
