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

import {
  getIReminderStats,
  ingestReminders,
  listPendingReminderSends,
  markReminderSendResult,
} from '@/features/ireminders';

const reminderSchema = z.object({
  reminderIdentifier: z.string().min(1),
  calendarIdentifier: z.string().min(1),
  title: z.string().nullish(),
  notes: z.string().nullish(),
  dueDate: z.string().nullish(),
  priority: z.number().int().min(0).max(9).nullish(),
  isCompleted: z.boolean(),
  modifiedAt: z.string().nullish(),
});

const syncRemindersSchema = z.object({
  reminders: z.array(reminderSchema),
});

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

export const iremindersClientRouter = new Hono()
  .post('/sync', async (c) => {
    const deviceId = c.get('deviceId');
    const payload = syncRemindersSchema.parse(await c.req.json());
    const result = await ingestReminders(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 getIReminderStats(deviceId) });
  })
  .get('/send-queue/pending', async (c) => {
    try {
      const deviceId = c.get('deviceId');
      const items = await listPendingReminderSends(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 reminder 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 markReminderSendResult({ 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 reminder send result',
          },
        },
        500,
      );
    }
  });
