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

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

const enqueueSchema = z.object({
  batchItemId: z.string(),
  deviceId: z.string(),
  toHandle: z.string(),
  body: z.string(),
  // Provenance: who composed the text vs what triggered the send. Optional for
  // back-compat; default to 'unknown' so every row carries an attribution.
  authoredBy: z.enum(SEND_ORIGINS).default('unknown'),
  dispatchedBy: z.enum(SEND_ORIGINS).default('unknown'),
});

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

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

      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,
      );
    }
  });
