const datetime = require("../../config/datetime");
const { database } = require("../../config/db");
const User = require("../model/User");

module.exports = class Controller {
    database = database;
    min_taka = 20;
    useType = {
        club: "club",
        user: "user",
        admin: "admin",
    }
    userStatus = {
        active: "active",
        block: "deactive",
    }
    dipositStatus = {
        pending: "pending",
        success: "success",
        cansel: "cansel"
    }
    transectionType = {
        deposit: "deposit",
        withdraw: "withdraw",
        transfer: "transfer",
        admin_update: {
            add: "admin_add",
            cut:"admin_cut"
        },
        bet: "bet",
        responsercomming: "sp_commition",
        club_commintion: "club_commition",
        bonus: "bonus",
    }
    getTaka = (taka) => {
        return parseFloat(taka.toString()).toFixed(2);
    }
    setting = () => {
        return this.database.table("setting").first();
    }
    bltransfer = (sender, reciver, taka, total,) => {
        const datetimex = datetime.time() + " " + datetime.today();
        return database.table("bltransfer").insert({ sender, reciver, taka, total, datetime: datetimex })
    }
    transection = async (user_id, debit, credit, total, type, message) => {
        return database.table("transection").insert({
            user_id, debit, credit, total, type, message, date: datetime.today(), time: datetime.time(),
        })
    }
    notifacation = (creator_id, reciver_id, title, message,) => {
        return database.table("notifaction").insert({
            creator_id, reciver_id, title, message, date: datetime.today(), time: datetime.time(),
        })
    }
    cutTakaFromUser = async (user_id, amount, type, message) => {
        const user = await User.find(user_id);
        let newBalance = this.getTaka(parseFloat(user.taka) - parseFloat(amount));
        if (newBalance < this.min_taka) throw new Error("Your min balance will be " + this.min_taka + " taka" + ", you can't cut more taka");
        const result = await database.raw(`UPDATE ${User.tablename} SET taka=taka - ? WHERE id= ? AND taka - ? >=?`, [this.getTaka(amount), user_id, this.getTaka(amount), this.min_taka]);
        if (result[0].affectedRows === 0) {
            throw new Error("Insufficient balance or minimum balance violation");
        }
        await this.transection(user_id, this.getTaka(amount), 0, newBalance, type, message);
    }
    addTakaToUser = async (user_id, amount, type, message) => {
        const user = await User.find(user_id);
        let newBalance = this.getTaka(parseFloat(user.taka) + parseFloat(amount));
        await database.raw(`UPDATE ${User.tablename} SET taka=taka + ? WHERE id= ?`, [this.getTaka(amount), user_id]);
        await this.transection(user_id, 0, this.getTaka(amount), newBalance, type, message);
    }
};