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

import { getDb, pgRunReturning } from '@/shared/db';
import type { SendQueueRow } from '@/entities/send-queue/types';

const enqueueSchema = z.object({
  batchItemId: z.string(),
  deviceId: z.string(),
  toHandle: z.string(),
  body: z.string(),
  // When true, the row is inserted with status='cancelled' instead of 'queued'
  // so MacSyncApp's send-queue poll will skip it. Used by health/integration
  // tests that need to exercise the route without dispatching to iMessage.
  dryRun: z.boolean().optional(),
});

export const sendQueueAdminRouter = new Hono()
  .post('/enqueue', async (c) => {
    try {
      const payload = enqueueSchema.parse(await c.req.json());
      const db = getDb();

      const status = payload.dryRun ? 'cancelled' : 'queued';
      const row = await pgRunReturning<SendQueueRow>(
        db,
        `
          INSERT INTO macsync.send_queue (device_id, to_handle, body, status, failure_reason)
          VALUES ($1, $2, $3, $4, $5)
          RETURNING id, device_id, to_handle, body, status, send_queue_id, sent_at, failure_reason, created_at, updated_at
        `,
        [
          payload.deviceId,
          payload.toHandle,
          payload.body,
          status,
          payload.dryRun ? 'dryRun: not dispatched' : null,
        ],
      );

      return c.json({
        success: true,
        data: {
          sendQueueId: row.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 message',
          },
        },
        500,
      );
    }
  });
