import { FastifyInstance, FastifyPluginOptions } from 'fastify';
import type { NotificationService } from '../modules/notification/index.js';

interface NotificationRouteOpts extends FastifyPluginOptions {
  notificationService: NotificationService;
}

export default async function notificationRoutes(app: FastifyInstance, opts: NotificationRouteOpts) {
  const { notificationService } = opts;

  app.get('/notifications', async (request, reply) => {
    const { limit, unreadOnly } = request.query as { limit?: string; unreadOnly?: string };
    try {
      const notifications = await notificationService.list({
        limit: limit ? parseInt(limit, 10) : undefined,
        unreadOnly: unreadOnly === 'true',
      });
      const unreadCount = await notificationService.getUnreadCount();
      return reply.send({ success: true, data: { notifications, unreadCount } });
    } catch (err: any) {
      return reply.status(500).send({ success: false, error: err.message });
    }
  });

  app.get('/notifications/unread-count', async (_request, reply) => {
    try {
      const count = await notificationService.getUnreadCount();
      return reply.send({ success: true, data: { unreadCount: count } });
    } catch (err: any) {
      return reply.status(500).send({ success: false, error: err.message });
    }
  });

  app.put('/notifications/:id/read', async (request, reply) => {
    const { id } = request.params as { id: string };
    try {
      await notificationService.markAsRead(id);
      return reply.send({ success: true });
    } catch (err: any) {
      return reply.status(500).send({ success: false, error: err.message });
    }
  });

  app.put('/notifications/read-all', async (_request, reply) => {
    try {
      await notificationService.markAllAsRead();
      return reply.send({ success: true });
    } catch (err: any) {
      return reply.status(500).send({ success: false, error: err.message });
    }
  });
}
