import { ExtractJwt, Strategy as JwtStrategy } from 'passport-jwt';

import tokenTypes from '@/modules/token/token.types.js';
import config from '@/shared/config/config.js';
import { IPayload } from '@/modules/token/token.interfaces.js';
import { validateUserToken } from '@/modules/auth/auth.helper';

const jwtStrategy = new JwtStrategy(
  {
    secretOrKey: config.jwt.secret,
    jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  },
  async (payload: IPayload, done) => {
    try {
      if (payload.type !== tokenTypes.ACCESS)
        throw new Error('Invalid token type');

      const user = await validateUserToken(payload);
      const userObj = user.toObject();

      userObj.id = userObj._id.toString();

      delete userObj.password;
      done(null, userObj);
    } catch (error) {
      done(error, false);
    }
  },
);

export default jwtStrategy;
