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

import { markConversationRead, markAllReplied, conversationReadState } from '@/features/read';

const markSchema = z.object({
  deviceId: z.string().uuid(),
  handle: z.string().min(1),
  /** Mark read through this instant; defaults to now. */
  readThrough: z.string().datetime().optional(),
  source: z.enum(['manual', 'outbox_send', 'all_replied']).optional(),
});

const allRepliedSchema = z.object({ deviceId: z.string().uuid() });
const deviceIdParam = z.string().uuid();

/**
 * Logical conversation read-state (Handoff 04). `markRead`/`markAllRepliedRead`
 * for an app/UI to flag handled threads. Never touches Apple's chat.db.
 */
export const readMyRouter = new Hono()
  .post('/', async (c) => {
    const parsed = markSchema.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, handle, readThrough, source } = parsed.data;
    const data = await markConversationRead(deviceId, handle, { readThrough, source });
    return c.json({ success: true, data });
  })
  .post('/all-replied', async (c) => {
    const parsed = allRepliedSchema.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 data = await markAllReplied(parsed.data.deviceId);
    return c.json({ success: true, data });
  })
  .get('/:handle', async (c) => {
    const deviceId = deviceIdParam.parse(c.req.query('deviceId') ?? '');
    const handle = z.string().min(1).parse(c.req.param('handle'));
    const data = await conversationReadState(deviceId, handle);
    return c.json({ success: true, data });
  });
