import type { Request, Response } from 'express';
import { listNotificationFeed, markNotificationAsRead } from '../services/communication.store';

const normalizeOptionalString = (value: unknown) =>
  typeof value === 'string' && value.trim() ? value.trim() : null;

export const getNotifications = async (req: Request, res: Response) => {
  const userId = normalizeOptionalString(req.query.userId);

  try {
    const notifications = await listNotificationFeed(userId);
    const unreadCount = notifications.filter((notification) => !notification.readAt).length;

    res.setHeader('X-Data-Source', 'local-fallback');
    return res.json({
      notifications,
      unreadCount,
    });
  } catch (error) {
    console.error('Error loading notification feed:', error);
    return res.status(500).json({ error: 'Error interno del servidor' });
  }
};

export const readNotification = async (req: Request, res: Response) => {
  const notificationId = normalizeOptionalString(req.params.notificationId);
  const userId = normalizeOptionalString(req.body?.userId);

  if (!notificationId) {
    return res.status(400).json({ error: 'Notificacion invalida' });
  }

  try {
    await markNotificationAsRead(notificationId, userId);
    return res.json({ ok: true });
  } catch (error) {
    console.error('Error marking notification as read:', error);
    return res.status(500).json({ error: 'Error interno del servidor' });
  }
};
