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

import {
  getINoteStats,
  ingestNotes,
  listPendingNoteSends,
  markNoteSendResult,
} from '@/features/inotes';

const noteSchema = z.object({
  noteIdentifier: z.string().min(1),
  folder: z.string().nullish(),
  name: z.string().nullish(),
  body: z.string().nullish(),
  modifiedAt: z.string().nullish(),
});

const syncNotesSchema = z.object({
  notes: z.array(noteSchema),
});

const sendResultSchema = z.object({
  status: z.enum(['sent', 'failed']),
  error: z.string().optional(),
});

export const inotesClientRouter = new Hono()
  .post('/sync', async (c) => {
    const deviceId = c.get('deviceId');
    const payload = syncNotesSchema.parse(await c.req.json());
    const result = await ingestNotes(deviceId, payload);
    return c.json({ success: true, data: result });
  })
  .get('/stats', async (c) => {
    const deviceId = c.get('deviceId');
    return c.json({ success: true, data: await getINoteStats(deviceId) });
  })
  .get('/send-queue/pending', async (c) => {
    try {
      const deviceId = c.get('deviceId');
      const items = await listPendingNoteSends(deviceId);
      return c.json({ success: true, data: { items } });
    } catch (err) {
      return c.json(
        {
          success: false,
          error: {
            code: 'send_queue_error',
            message: err instanceof Error ? err.message : 'failed to fetch pending note sends',
          },
        },
        500,
      );
    }
  })
  .post('/send-queue/:id/result', async (c) => {
    try {
      const id = c.req.param('id');
      const body = sendResultSchema.parse(await c.req.json());
      await markNoteSendResult({ id, status: body.status, error: body.error ?? null });
      return c.json({ success: true, data: {} });
    } 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: 'send_queue_error',
            message: err instanceof Error ? err.message : 'failed to mark note send result',
          },
        },
        500,
      );
    }
  });
