const datetime = require("../../config/datetime");
const { AppEvent, AppEventType } = require("../event/my.event");
const Admin = require("../model/Admin");
const Method = require("../model/Method");
const User = require("../model/User");
const Widthdrow = require("../model/Widthdrow");
const Controller = require("./Controller");
const bcrypt = require("bcrypt");
module.exports = new class WidthdrowController extends Controller {
    request = async (req, res, next) => {
        try {
            // method: 30, account: '34534534', password: '12345678', amount: 444
            const { method, account, password, amount } = req.body;
            if (!method || !account || !password || !amount) return next("input data not-found!");
            const methods = await Method.find(method);
            const user = req.user;
            const setting = await this.setting();
            const checkpassstatus = await bcrypt.compare(password, user.pass);
            if (!checkpassstatus) return next("invalid password!");
            if (parseInt(setting.widthdrow_min) > parseInt(amount) || parseInt(setting.widthdrow_max) < parseInt(amount)) return next(`Your min widthdrow ${this.getTaka(setting.widthdrow_min)} and max ${setting.widthdrow_max}`)
            const checkactiveRequ = await Widthdrow.where("status", Widthdrow.status.pending).andWhere("user_id", user.id);
            if (checkactiveRequ.length > 0) return next("Your widthdrow request all ready active!")
            if (user.wd_permition != "1") return next("Your widthdrow parmition deactive!");
            if (setting.wd_parmition == "deactive") return next("Sometime widthdrow inactive!");
            // check user taka
            await this.cutTakaFromUser(user.id, amount, this.transectionType.withdraw, "withdraw request");
            const payload = {
                user_id: user.id,
                method_name: methods.name,
                user_type: user.role,
                user_number: account,
                taka: this.getTaka(amount),
                request_date: datetime.today() + " " + datetime.time()
            }
            await Widthdrow.add(payload);
            AppEvent.emit(AppEventType.NOTIFACATION);
            res.success("successfull");
        } catch (error) {
            return next(error.toString());
        }
    }
    history = async (req, res, next) => {
        try {
            const datas = await Widthdrow.where("user_id", "=", req.user.id);
            const send = [];
            // Date	Method	Account	Amount	Status
            for (const data of datas) {
                send.push({
                    Date: data.request_date,
                    Method: `${data.method_name}`,
                    Account: data.user_number,
                    Role: data.user_type,
                    Amount: this.getTaka(data.taka),
                    Status: data.status
                })
            }
            return res.success(`data success`, send);
        } catch (error) {
            return next(error);
        }
    }
    data = async () => {
        const datas = await Widthdrow.get();
        const alldata = await Promise.all(
            datas.map(async (item) => {
                let accesptor_name = null;
                let user_name = (await User.find(item.user_id))?.name || "";
                if (item.accesptor_id) {
                    const accesptor = await Admin.find(item.accesptor_id);
                    accesptor_name = accesptor?.name || null;
                }
                return {
                    ...item,
                    user_name,
                    accesptor_id: accesptor_name,
                };
            })
        );
        return alldata;
    }
    index = async (req, res, next) => {
        try {
            return res.success(`data success`, await this.data());
        } catch (error) {
            return next(error);
        }
    }
    old = async (req, res, next) => {
        try {
            const data = (await this.data()).filter((item) => item.status != Widthdrow.status.pending);
            return res.success(`data success`, data);
        } catch (error) {
            return next(error);
        }
    }
    accespt = async (req, res, next) => {
        try {
            const id = req.params.id;
            const findDeposit = await Widthdrow.find(id);
            if (findDeposit.status != Widthdrow.status.pending) return next("invalid id");
            const datetim = datetime.today() + " " + datetime.time();
            const admin = req.user;
            // Widthdrow dp info
            await Widthdrow.update(id, value => {
                return {
                    accespt_date: datetim,
                    accesptor_id: admin.id,
                    status: Widthdrow.status.success
                }
            })
            await this.notifacation(admin.id, findDeposit.id, "Widthdrow Information", `Your widthdrow request success ${this.getTaka(findDeposit.taka)}`);
            // responce
            AppEvent.emit(AppEventType.NOTIFACATION);

            return res.success('Widthdrow success');
        } catch (error) {
            return next(error);
        }
    }
    cansel = async (req, res, next) => {
        try {
            const id = req.params.id;
            const findDeposit = await Widthdrow.find(id);
            if (findDeposit.status != Widthdrow.status.pending) return next("invalid id");
            const datetim = datetime.today() + " " + datetime.time();
            const admin = req.user;
            // update dp info
            await Widthdrow.update(id, value => {
                return {
                    accespt_date: datetim,
                    accesptor_id: admin.id,
                    status: Widthdrow.status.cansel
                }
            })
            await this.addTakaToUser(findDeposit.user_id, findDeposit.taka, this.transectionType.withdraw, `Widthdrow cansel`);
            AppEvent.emit(AppEventType.NOTIFACATION);

            return res.success('Widthdrow cansel');
        } catch (error) {
            return next(error);
        }
    }

};  