import jwt from "jsonwebtoken";
import { env } from "../config/env.js";
import { getDb } from "../config/db.js";

export const authenticate = async (req, res, next) => {
  const header = req.headers.authorization;

  if (!header?.startsWith("Bearer ")) {
    return res.status(401).json({ message: "Authentication required" });
  }

  try {
    const token = header.split(" ")[1];
    const payload = jwt.verify(token, env.jwtSecret);
    const db = getDb();
    const [rows] = await db.execute(
      `SELECT u.id, u.name, u.email, u.role, u.notary_id, n.name AS notary_name, n.region, n.district, n.category, n.expired_date
       FROM users u
       LEFT JOIN notaries n ON n.id = u.notary_id
       WHERE u.id = ? AND u.is_active = 1`,
      [payload.userId]
    );
    const user = rows[0];

    if (!user) {
      return res.status(401).json({ message: "User not found" });
    }

    req.user = user;
    next();
  } catch (error) {
    return res.status(401).json({ message: "Invalid token" });
  }
};

export const requireRole = (...allowedRoles) => (req, res, next) => {
  const userRole = String(req.user.role || "").trim().toLowerCase();
  if (!allowedRoles.includes(userRole)) {
    console.error(`[Access Denied] User ID: ${req.user.id}, Role: "${userRole}", Allowed: [${allowedRoles.join(", ")}], Path: ${req.originalUrl}`);
    return res.status(403).json({ message: "Access denied" });
  }

  next();
};

export const requireExpirationCheck = (req, res, next) => {
  if (!req.user.notary_id || !req.user.expired_date) {
    console.log("Skipping expiration check", !!req.user.notary_id, !!req.user.expired_date);
    return next(); // Not a notary user or no expiry date set, bypass check
  }

  const currentDate = new Date();
  const expiredDate = new Date(req.user.expired_date);
  
  // Calculate days difference (current - expired)
  const diffTime = currentDate - expiredDate;
  const daysOverdue = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  console.log("Expiration check: ", expiredDate, "Days overdue:", daysOverdue);

  if (daysOverdue > 3) {
    return res.status(403).json({ 
      message: "Your notary license has expired for more than 3 days. Account is locked. Please contact the Ministry of Justice to renew." 
    });
  }

  if (daysOverdue > 0 && ['POST', 'PUT', 'PATCH', 'DELETE'].includes(req.method)) {
     return res.status(403).json({ 
      message: "Your notary license has expired. You are in a 3-day view-only grace period. You cannot make any changes." 
    });
  }

  next();
};
