import { BadRequestException, Logger } from "@nestjs/common";
import { EntityRepository, ILike, Like, Repository } from "typeorm";
import { TempSignUpDto } from "./dto/temp-sign-up.dto";
import { Pcduser } from "./pcduser.entity";
import * as bcrypt from 'bcrypt';
import { AuthCreadentialsDto } from "./dto/auth-credentials.dto";
import { PcduserDto } from "src/auth/dto/pcd-user.dto";

@EntityRepository(Pcduser)
export class PcduserRepository extends Repository<Pcduser>{
    private logger = new Logger('Pcduser Repo'); // for logging
    async updateRefreshToken(userId: string, refreshToken: string) {
        const user = await this.findOne({ userId: userId });
        user.refreshtoken = refreshToken;
        this.save(user);
    }

    async signUp(authCredentials: TempSignUpDto, customerMobileNo, memberNo?, bankId?, secuLevel?): Promise<any> {

        const salt = await bcrypt.genSalt();
        const tsalt = await bcrypt.genSalt();
        const user = new Pcduser();
        // user.userId = authCredentials.userId;
        let maxCode: number = 10001;
        const maxRow: PcduserDto = await this.findOne({
            where: { userId: Like('1%') },
            order: {
                "userId": "DESC"
            }
        });

        if (maxRow) {
            maxCode = parseInt(maxRow.userId) + 1;
        }
        if (!customerMobileNo) {
            user.status = 'V';
        }
        else {
            user.status = 'N';
            user.mobileNumber = customerMobileNo;
        }
        user.userId = maxCode.toString();
        user.userName = authCredentials.username;
       
        user.email = authCredentials.email;
        user.createdBy = "SYSTEM";
        user.modifiedBy = "SYSTEM";
        user.groupOrUser = 'U';
       
        user.secuLevel = secuLevel;
        user.salt = salt;
        user.pass = await this.hashPassword(authCredentials.password, salt);
        user.tSalt = tsalt;
        user.tPass = await this.hashPassword(authCredentials.tpassword, tsalt);
        user.bankId = bankId;
        try {
            return await user.save();
        } catch (error) {
            // if(error.code==23505) not working in orcale
            throw new BadRequestException(error.message);
        }
    }


    async getEagerColumns(): Promise<string[]> {
        /* 
        For getting Eager true columns having Many to One relations.
        We need to remove the eager columns before insertions or updations or it will not allow to save data (But save message will show, but data not updated) 
         */
        const COLUMNS: string[] = [];
        for (let columnProperty of this.metadata.eagerRelations) {
            COLUMNS.push(columnProperty.propertyName);
        }
        return COLUMNS;
    }



    async encryptPassword(password: string, salt: string): Promise<string> {
        return await this.hashPassword(password, salt);
    }



    private async hashPassword(password: string, salt: string): Promise<string> {
        return await bcrypt.hash(password, salt);
    }

}