/**
 * Authentication Utilities
 * 
 * Ez a fájl példa helper függvényeket tartalmaz az auth implementációhoz.
 * Használhatod ezeket a függvényeket az AuthController-ben és middleware-ekben.
 */

import jwt from 'jsonwebtoken';
import bcrypt from 'bcrypt';

/**
 * JWT Token Generálás
 */

export function generateAccessToken(user) {
  const payload = {
    userId: user.id,
    email: user.email,
    role: user.role
  };

  return jwt.sign(
    payload,
    process.env.JWT_SECRET,
    { expiresIn: process.env.JWT_EXPIRES_IN || '7d' }
  );
}

export function generateRefreshToken(user) {
  const payload = {
    userId: user.id
  };

  return jwt.sign(
    payload,
    process.env.JWT_REFRESH_SECRET,
    { expiresIn: process.env.JWT_REFRESH_EXPIRES_IN || '30d' }
  );
}

/**
 * JWT Token Validálás
 */

export function verifyAccessToken(token) {
  try {
    return jwt.verify(token, process.env.JWT_SECRET);
  } catch (error) {
    if (error.name === 'TokenExpiredError') {
      throw new Error('Token expired');
    }
    if (error.name === 'JsonWebTokenError') {
      throw new Error('Invalid token');
    }
    throw error;
  }
}

export function verifyRefreshToken(token) {
  try {
    return jwt.verify(token, process.env.JWT_REFRESH_SECRET);
  } catch (error) {
    throw new Error('Invalid refresh token');
  }
}

/**
 * Token Kiolvasás Request-ből
 */

export function extractTokenFromRequest(req) {
  // 1. Cookie-ból
  if (req.cookies && req.cookies.accessToken) {
    return req.cookies.accessToken;
  }

  // 2. Authorization header-ből
  const authHeader = req.headers.authorization;
  if (authHeader && authHeader.startsWith('Bearer ')) {
    return authHeader.substring(7);
  }

  return null;
}

/**
 * Jelszó Hash-elés és Validálás
 */

export async function hashPassword(plainPassword) {
  const saltRounds = 10;
  return await bcrypt.hash(plainPassword, saltRounds);
}

export async function verifyPassword(plainPassword, hashedPassword) {
  return await bcrypt.compare(plainPassword, hashedPassword);
}

/**
 * Cookie Beállítás
 */

export function setAuthCookies(res, accessToken, refreshToken) {
  const cookieOptions = {
    httpOnly: true,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'strict'
  };

  // Access token cookie - 7 nap
  res.cookie('accessToken', accessToken, {
    ...cookieOptions,
    maxAge: 7 * 24 * 60 * 60 * 1000
  });

  // Refresh token cookie - 30 nap
  res.cookie('refreshToken', refreshToken, {
    ...cookieOptions,
    maxAge: 30 * 24 * 60 * 60 * 1000
  });
}

export function clearAuthCookies(res) {
  res.clearCookie('accessToken');
  res.clearCookie('refreshToken');
}

/**
 * Input Validáció
 */

export function isValidEmail(email) {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  return emailRegex.test(email);
}

export function isValidPassword(password) {
  // Minimum 8 karakter
  return password && password.length >= 8;
}

export function validateRegisterInput(data) {
  const errors = [];

  if (!data.email || !isValidEmail(data.email)) {
    errors.push('Valid email is required');
  }

  if (!data.username || data.username.length < 3) {
    errors.push('Username must be at least 3 characters');
  }

  if (!data.password || !isValidPassword(data.password)) {
    errors.push('Password must be at least 8 characters');
  }

  return {
    isValid: errors.length === 0,
    errors
  };
}

export function validateLoginInput(data) {
  const errors = [];

  if (!data.password) {
    errors.push('Password is required');
  }

  if (!data.email && !data.username) {
    errors.push('Email or username is required');
  }

  return {
    isValid: errors.length === 0,
    errors
  };
}

/**
 * Redis Session Management (Opcionális)
 */

import { redis } from '../database/redis.js';

export async function createSession(userId, sessionData) {
  const sessionKey = `session:${userId}`;
  const ttl = 7 * 24 * 60 * 60; // 7 nap másodpercben

  await redis.set(
    sessionKey,
    JSON.stringify({
      userId,
      loginTime: new Date().toISOString(),
      ...sessionData
    }),
    'EX',
    ttl
  );
}

export async function getSession(userId) {
  const sessionKey = `session:${userId}`;
  const session = await redis.get(sessionKey);

  if (!session) {
    return null;
  }

  return JSON.parse(session);
}

export async function deleteSession(userId) {
  const sessionKey = `session:${userId}`;
  await redis.del(sessionKey);
}

export async function sessionExists(userId) {
  const sessionKey = `session:${userId}`;
  const exists = await redis.exists(sessionKey);
  return exists === 1;
}
