import { HttpException, HttpStatus, Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Types } from 'mongoose';
import { ModelsService } from 'src/models/models.service';

@Injectable()
export class AuthService {
    constructor(
        private model: ModelsService
    ) {
    }

    async verifyToken(payload: any) {
        let { _id: user_id, token_gen_at } = payload;
        console.log(user_id, "userid---------");
        let query = {
            user_id: new Types.ObjectId(user_id),
        }
        let projection = { __v: 0 }
        let option = { lean: true }
        let fetch_data: any = await this.model.SessionModel.find(query, projection, option)
        if (fetch_data.length) {
            return fetch_data
        }
        else {
            throw new UnauthorizedException("Unauthorized user.")
        }
    }
}

@Injectable()
export class SocketDisConnect {
    constructor(
        private jwtservice: JwtService,
        private model: ModelsService,
    ) { }

    verify_token = async (token: any) => {
        if (!token) throw new HttpException({ message: "Unauthorized User" }, HttpStatus.UNAUTHORIZED);
        try {
            const new_token = token.split(' ')[1];
            let projection = { _v: 0 }
            let options = { lean: true }
            let secretKey = process.env.SECRET_KEY
            const payload = await this.jwtservice.verifyAsync(new_token, { secret: secretKey });
            let { scope } = payload;

            let data = await this.verifyToken(payload);
            if (!data) throw new HttpException({ message: "Unauthorized User" }, HttpStatus.UNAUTHORIZED);
            let { _id } = payload;
            let query = { _id: _id }
            let fetch_user = await this.model.UserModel.findOne(query, projection, options);
            if (!fetch_user)
                throw new HttpException({ message: "Unauthorized User" }, HttpStatus.UNAUTHORIZED);
            return fetch_user
        }
        catch (e) {
            throw e;
        }
    }


    async verifyToken(payload: any) {
        let { scope } = payload;
        let query;
        if (scope == "USER") {
            let { _id: user_id, token_gen_at } = payload;
            query = {
                user_id: new Types.ObjectId(user_id),
                token_gen_at: token_gen_at
            }
        }
        let projection = { __v: 0 }
        let option = { lean: true }
        let fetch_data: any = await this.model.SessionModel.find(query, projection, option)
        if (fetch_data.length) {
            return fetch_data
        }
        else {
            throw new UnauthorizedException("Unauthorized user.")
        }
    }
}