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

import { enqueueReply, getReply, outboxStats } from '@/features/outbox';

const deviceIdParam = z.string().uuid();

const enqueueSchema = z.object({
  deviceId: z.string().uuid(),
  recipient: z.string().min(3),
  body: z.string().min(1).max(4000),
  channelPref: z.enum(['auto', 'imessage', 'sms']).optional(),
  /** Epoch ms of the lead's last inbound — drives smart scheduling. */
  recvAt: z.number().int().positive().optional(),
  /** Explicit ISO send-eligible time; overrides the scheduler. */
  notBefore: z.string().datetime().optional(),
  dedupeKey: z.string().min(1).max(256).optional(),
  maxAttempts: z.number().int().positive().max(10).optional(),
  /** Mark the recipient's thread read once this reply is confirmed sent. */
  markReadOnSend: z.boolean().optional(),
});

export const outboxMyRouter = new Hono()
  .post('/', async (c) => {
    const parsed = enqueueSchema.safeParse(await c.req.json().catch(() => null));
    if (!parsed.success) {
      return c.json({ success: false, error: { code: 'validation_error', issues: parsed.error.flatten() } }, 400);
    }
    const { deviceId, ...input } = parsed.data;
    const result = await enqueueReply(deviceId, input);
    return c.json({ success: true, data: result }, result.deduped ? 200 : 201);
  })
  .get('/stats', async (c) => {
    const deviceId = deviceIdParam.parse(c.req.query('deviceId') ?? '');
    return c.json({ success: true, data: await outboxStats(deviceId) });
  })
  .get('/:id', async (c) => {
    const id = z.string().uuid().parse(c.req.param('id'));
    const row = await getReply(id);
    if (!row) return c.json({ success: false, error: { code: 'not_found' } }, 404);
    return c.json({ success: true, data: row });
  });
