import jwt from 'jsonwebtoken';
import { AuthenticationError } from './errors.js';

/**
 * Generuje access JWT token
 * @param {Object} payload - User data (id, username, role)
 * @returns {string} JWT token
 */
export const generateAccessToken = (payload) => {
  return jwt.sign(payload, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_IN || '1h',
  });
};

/**
 * Generuje refresh JWT token
 * @param {Object} payload - User data (id)
 * @returns {string} Refresh token
 */
export const generateRefreshToken = (payload) => {
  return jwt.sign(payload, process.env.JWT_REFRESH_SECRET, {
    expiresIn: process.env.JWT_REFRESH_EXPIRES_IN || '7d',
  });
};

/**
 * Overí access JWT token
 * @param {string} token - JWT token
 * @returns {Object} Decoded payload
 * @throws {Error} Ak je token neplatný alebo expirovaný
 */
export const verifyAccessToken = (token) => {
  try {
    return jwt.verify(token, process.env.JWT_SECRET);
  } catch (error) {
    if (error.name === 'TokenExpiredError') {
      throw new AuthenticationError('Token expiroval');
    }
    if (error.name === 'JsonWebTokenError') {
      throw new AuthenticationError('Neplatný token');
    }
    throw error;
  }
};

/**
 * Overí refresh JWT token
 * @param {string} token - Refresh token
 * @returns {Object} Decoded payload
 * @throws {Error} Ak je token neplatný alebo expirovaný
 */
export const verifyRefreshToken = (token) => {
  try {
    return jwt.verify(token, process.env.JWT_REFRESH_SECRET);
  } catch (error) {
    if (error.name === 'TokenExpiredError') {
      throw new AuthenticationError('Refresh token expiroval');
    }
    if (error.name === 'JsonWebTokenError') {
      throw new AuthenticationError('Neplatný refresh token');
    }
    throw error;
  }
};

/**
 * Vytvorí obidva tokeny (access + refresh)
 * @param {Object} user - User object
 * @returns {Object} { accessToken, refreshToken }
 */
export const generateTokenPair = (user) => {
  const payload = {
    id: user.id,
    username: user.username,
    role: user.role,
  };

  const refreshPayload = {
    id: user.id,
  };

  return {
    accessToken: generateAccessToken(payload),
    refreshToken: generateRefreshToken(refreshPayload),
  };
};
