import { Hono } from 'hono';
import { NotificationQuerySchema } from '../types/index';
import * as notifService from '../services/notification.service';

export const notificationsRouter = new Hono();

// ─── GET /v1/notifications ──────────────────────────────
notificationsRouter.get('/', async (c) => {
  try {
    const query = NotificationQuerySchema.parse(c.req.query());
    const auth = c.get('auth');
    const result = await notifService.listNotifications(auth.userId, query);
    return c.json({ success: true, data: result.items, meta: result.meta });
  } catch (err: any) {
    return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: err.message } }, 500);
  }
});

// ─── POST /v1/notifications/:id/read ────────────────────
notificationsRouter.post('/:id/read', async (c) => {
  try {
    const auth = c.get('auth');
    const updated = await notifService.markRead(c.req.param('id'), auth.userId);
    if (!updated) return c.json({ success: false, error: { code: 'NOT_FOUND', message: 'Notification not found' } }, 404);
    return c.json({ success: true, data: updated });
  } catch (err: any) {
    return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: err.message } }, 500);
  }
});

// ─── POST /v1/notifications/:id/dismiss ─────────────────
notificationsRouter.post('/:id/dismiss', async (c) => {
  try {
    const auth = c.get('auth');
    const updated = await notifService.dismiss(c.req.param('id'), auth.userId);
    if (!updated) return c.json({ success: false, error: { code: 'NOT_FOUND', message: 'Notification not found' } }, 404);
    return c.json({ success: true, data: updated });
  } catch (err: any) {
    return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: err.message } }, 500);
  }
});
