import { pool } from "../config/db.js";
import { ApiError } from "../utils/ApiError.js";
import { getJwtUserId } from "../middlewares/authMiddleware.js";

function toPositiveInt(value, fieldName) {
  const parsed = Number(value);
  if (!Number.isInteger(parsed) || parsed <= 0) {
    throw new ApiError(400, `${fieldName} must be a positive integer`);
  }
  return parsed;
}

export async function listMyHandoverNotifications(req, res, next) {
  try {
    const userIdRaw = getJwtUserId(req.user);
    const userId = Number(userIdRaw);
    if (!Number.isInteger(userId) || userId <= 0) {
      throw new ApiError(401, "Could not resolve signed-in user");
    }

    const [rows] = await pool.query(
      `SELECT
         n.notification_id,
         n.recipient_user_id,
         n.permit_id,
         n.submission_id,
         n.handed_by_user_id,
         n.permit_number,
         n.message,
         n.read_at,
         n.created_at,
         handed.employee_name AS handed_by_name
       FROM ptw_handover_notifications n
       LEFT JOIN users handed ON handed.user_id = n.handed_by_user_id
       WHERE n.recipient_user_id = ?
       ORDER BY n.created_at DESC
       LIMIT 50`,
      [userId]
    );

    res.json({
      data: rows,
      unread_count: rows.filter((row) => !row.read_at).length
    });
  } catch (err) {
    next(err);
  }
}

export async function markHandoverNotificationRead(req, res, next) {
  try {
    const userIdRaw = getJwtUserId(req.user);
    const userId = Number(userIdRaw);
    if (!Number.isInteger(userId) || userId <= 0) {
      throw new ApiError(401, "Could not resolve signed-in user");
    }

    const notificationId = toPositiveInt(req.params.notification_id, "notification_id");
    const [result] = await pool.query(
      `UPDATE ptw_handover_notifications
       SET read_at = COALESCE(read_at, NOW())
       WHERE notification_id = ? AND recipient_user_id = ?`,
      [notificationId, userId]
    );

    if (!result.affectedRows) {
      throw new ApiError(404, "Notification not found");
    }

    res.json({ message: "Notification marked as read" });
  } catch (err) {
    next(err);
  }
}

export async function markAllHandoverNotificationsRead(req, res, next) {
  try {
    const userIdRaw = getJwtUserId(req.user);
    const userId = Number(userIdRaw);
    if (!Number.isInteger(userId) || userId <= 0) {
      throw new ApiError(401, "Could not resolve signed-in user");
    }

    await pool.query(
      `UPDATE ptw_handover_notifications
       SET read_at = COALESCE(read_at, NOW())
       WHERE recipient_user_id = ? AND read_at IS NULL`,
      [userId]
    );

    res.json({ message: "All notifications marked as read" });
  } catch (err) {
    next(err);
  }
}
