const {
    UserModel,
    BusinessModel
} = global.config
const {
    spaces,
    escape,
    setCooldown
} = global.utils

module.exports = async (ctx) => {
    let user = await UserModel.findByPk(ctx.from.id)
    let business = await BusinessModel.findOne({
      where: {
        owner: user.business.id.toString()
      }
    })
    if (user.business == null) return await ctx.reply(`Вы не работаете в организации.`)
    let timer = user.worktime
    let cooldown = setCooldown(user, 3600, timer)
    if (user.worktime > cooldown.currentTime) return ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `📛 Работа в организации будет доступна через ${cooldown.timeLeftInMinutes} минут(у/ы)`, {show_alert: true});
    if (business.materials < 10) return ctx.telegram.answerCbQuery(ctx.callbackQuery.id, `📛 В организации недостаточно материалов для отработки.`);
    user.worktime = cooldown.endTime
    user.business = {
        id: user.business.id,
        checks: user.business.checks + 1,
        percent: user.business.percent
    }
    business.materials -= 10
    business.checks += 1
    await user.save()
    await business.save()
    if (business.owner == ctx.from.id){
        let text = ``
        for (n = 0; n < business.users.length; n++) { // Процент выплаты участникам
            users = await UserModel.findByPk(business.users[n])
            text += `${users.username} - ${users.business.checks} [${users.business.percent}%]\n`
        }
        return await ctx.editMessageText(`🏭 Ваша организация\n_${business.name}_\n💹 Баланс: ₽${escape(spaces(business.balance))}\n🧰 Сырье: ${business.materials} \n👥 Рабочих: ${business.users.length}\n🔨 Отработок: ${business.checks}\n${escape(text)}\n\nВаши отработки: ${user.business.checks}`,
        { 
            reply_markup: {
                inline_keyboard: [
                    [{
                        text: `📶 Отработка`,
                        callback_data: "workoff"
                    }, {
                        text: `💸 Payday`,
                        callback_data: "payday"
                    }]
                ]},
            parse_mode: `MarkdownV2`
        }
        )
    }else{
        return await ctx.editMessageText(`🏭 Организация\n_${business.name}_\n💹 Баланс: ₽${escape(spaces(business.balance))}\n🧰 Сырье: ${business.materials}\n👥 Рабочих: ${business.users.length}\n\nВаши отработки: ${user.business.checks}`,
        { 
            reply_markup: {
                inline_keyboard: [
                    [{
                        text: `📶 Отработка`,
                        callback_data: "workoff"
                    }, {
                        text: `⬅️ Покинуть`,
                        callback_data: "покинуть"
                    }]
                ]},
            parse_mode: `MarkdownV2`
        }
        ) 
    }
}