const jwt = require('jsonwebtoken');

class JWTConfig {
  constructor() {
    this.accessTokenSecret = process.env.JWT_ACCESS_SECRET || 'access-secret-key-2024-tech4biz';
    this.refreshTokenSecret = process.env.JWT_REFRESH_SECRET || 'refresh-secret-key-2024-tech4biz';
    this.accessTokenExpiry = process.env.JWT_ACCESS_EXPIRY || '24h';
    this.refreshTokenExpiry = process.env.JWT_REFRESH_EXPIRY || '7d';
  }

  generateAccessToken(payload) {
    return jwt.sign(payload, this.accessTokenSecret, {
      expiresIn: this.accessTokenExpiry,
      issuer: 'tech4biz-auth',
      audience: 'tech4biz-users'
    });
  }

  generateRefreshToken(payload) {
    return jwt.sign(payload, this.refreshTokenSecret, {
      expiresIn: this.refreshTokenExpiry,
      issuer: 'tech4biz-auth',
      audience: 'tech4biz-users'
    });
  }

  verifyAccessToken(token) {
    try {
      return jwt.verify(token, this.accessTokenSecret, {
        issuer: 'tech4biz-auth',
        audience: 'tech4biz-users'
      });
    } catch (error) {
      throw new Error('Invalid access token');
    }
  }

  verifyRefreshToken(token) {
    try {
      return jwt.verify(token, this.refreshTokenSecret, {
        issuer: 'tech4biz-auth',
        audience: 'tech4biz-users'
      });
    } catch (error) {
      throw new Error('Invalid refresh token');
    }
  }

  generateTokenPair(user) {
    const payload = {
      userId: user.id,
      email: user.email,
      username: user.username,
      role: user.role || 'user'
    };

    const accessToken = this.generateAccessToken(payload);
    const refreshToken = this.generateRefreshToken({ userId: user.id });

    return {
      accessToken,
      refreshToken,
      expiresIn: this.accessTokenExpiry
    };
  }

  extractTokenFromHeader(authHeader) {
    if (!authHeader) {
      throw new Error('Authorization header missing');
    }

    if (!authHeader.startsWith('Bearer ')) {
      throw new Error('Invalid authorization header format');
    }

    return authHeader.substring(7); // Remove 'Bearer ' prefix
  }

  decodeToken(token) {
    try {
      return jwt.decode(token, { complete: true });
    } catch (error) {
      throw new Error('Invalid token format');
    }
  }

  getTokenExpiry(token) {
    const decoded = this.decodeToken(token);
    return decoded.payload.exp * 1000; // Convert to milliseconds
  }

  isTokenExpired(token) {
    try {
      const expiry = this.getTokenExpiry(token);
      return Date.now() >= expiry;
    } catch (error) {
      return true; // Treat invalid tokens as expired
    }
  }
}

module.exports = new JWTConfig();