const userModel = require("../models/userModel");
const adminModel = require("../models/adminModel");
const bcrypt = require("bcrypt");

const validateUser = async (req) => {
    console.log("User Email :", req.body.email );
    const existing = await userModel.findOne({ email: req.body.email });
    if(existing){
        return true
    } else {
        return false
    };
};

const validateAdmin = async (req) => {
    console.log("Admin Email :", req.body);
    const existing = await adminModel.findOne({ email: req.body.email });
    if(existing){
        return true
    } else {
        return false
    }
};

const validateAge = async (req) => {
    const { DOB } = req.body;

    const parts = DOB.split("-");
    const [ day, month, year ] = parts.map(Number);
    const birthDate = new Date(year, month -1, day);

    const today = new Date();
    let age = today.getFullYear() - birthDate.getFullYear();
    const m = today.getMonth() - birthDate.getMonth();
    if( m < 0 || (m === 0 && today.getDate()) < birthDate.getDate()){
        age--;
    };
    console.log("Age :", age);
    if(age < 21){
        console.log("Age is below 21")
        return false
    } else {
        console.log("Age is Above 21")
        return true
    };
};

const verifyPassword = async (password, hash) => {
    let match = await bcrypt.compare(password, hash);
    console.log("testing :", match);
    return match
};

module.exports = {
    validateAge,
    validateUser,
    validateAdmin,
    verifyPassword
};

