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

import {
  reminderSendPayloadSchema,
  REMINDER_SEND_ACTIONS,
} from '@/entities/reminderSendItem';
import { enqueueReminderChange } from '@/features/ireminders';

const enqueueSchema = z.object({
  deviceId: z.string().min(1),
  action: z.enum(REMINDER_SEND_ACTIONS),
  payload: reminderSendPayloadSchema,
});

export const reminderSendQueueAdminRouter = new Hono().post('/enqueue', async (c) => {
  try {
    const body = enqueueSchema.parse(await c.req.json());
    const { id } = await enqueueReminderChange(body);
    return c.json({ success: true, data: { id } });
  } catch (err) {
    if (err instanceof z.ZodError) {
      return c.json(
        {
          success: false,
          error: { code: 'validation_error', message: 'invalid request payload', issues: err.issues },
        },
        400,
      );
    }
    return c.json(
      {
        success: false,
        error: {
          code: 'enqueue_error',
          message: err instanceof Error ? err.message : 'failed to enqueue reminder action',
        },
      },
      500,
    );
  }
});
