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

import {
  calendarSendPayloadSchema,
  CALENDAR_SEND_ACTIONS,
} from '@/entities/calendarSendItem';
import { enqueueEventChange } from '@/features/ical/sendService';

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

export const calendarSendQueueAdminRouter = new Hono().post('/enqueue', async (c) => {
  try {
    const body = enqueueSchema.parse(await c.req.json());
    const { id } = await enqueueEventChange(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 calendar action',
        },
      },
      500,
    );
  }
});
