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

import { noteSendPayloadSchema, NOTE_SEND_ACTIONS } from '@/entities/noteSendItem';
import { enqueueNoteChange } from '@/features/inotes';

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

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