import cookie from "cookie";
import * as jwt from "jsonwebtoken";
import { Action } from 'routing-controllers';
import { getConnectionManager } from 'typeorm';
import { config } from '../config';
import { IllegalJWTError, UserDisabledError, UserNonexistantOrRefreshtokenInvalidError } from '../errors/AuthError';
import { JwtCreator, JwtUser } from '../jwtcreator';
import { User } from '../models/entities/User';

/**
 * TODO:
 */
const UserChecker = async (action: Action) => {
    let jwtPayload = undefined
    try {
        let provided_token = "" + action.request.headers["authorization"].replace("Bearer ", "");
        jwtPayload = <any>jwt.verify(provided_token, config.jwt_secret);
        jwtPayload = jwtPayload["userdetails"];
    } catch (error) {
        jwtPayload = await refresh(action);
    }

    const user = await getConnectionManager().get().getRepository(User).findOne({ id: jwtPayload["id"], refreshTokenCount: jwtPayload["refreshTokenCount"] })
    if (!user) { throw new UserNonexistantOrRefreshtokenInvalidError() }
    if (user.enabled == false) { throw new UserDisabledError(); }
    return user;
};

/**
 * Handles soft-refreshing of access-tokens.
 * @param action Routing-Controllers action object that provides request and response objects among other stuff.
 */
const refresh = async (action: Action) => {
    let refresh_token = undefined;
    try {
        refresh_token = cookie.parse(action.request.headers["cookie"])["lfk_backend__refresh_token"];
    }
    catch {
        throw new IllegalJWTError();
    }

    let jwtPayload = undefined;
    try {
        jwtPayload = <any>jwt.verify(refresh_token, config.jwt_secret);
    } catch (error) {
        throw new IllegalJWTError();
    }

    const user = await getConnectionManager().get().getRepository(User).findOne({ id: jwtPayload["id"], refreshTokenCount: jwtPayload["refreshTokenCount"] }, { relations: ['permissions', 'groups', 'groups.permissions'] })
    if (!user) { throw new UserNonexistantOrRefreshtokenInvalidError() }
    if (user.enabled == false) { throw new UserDisabledError(); }

    let newAccess = JwtCreator.createAccess(user);
    action.response.header("authorization", "Bearer " + newAccess);

    return await new JwtUser(user);
}
export default UserChecker;