const sequelize = global.database
const {
    rarecars,
    simplecars,
    UserModel,
    PropertyModel
} = global.config
const {
    spaces,
    rand
} = global.utils

module.exports = async (ctx) => {
    let user = await UserModel.findByPk(ctx.from.id)
    let property = await PropertyModel.findByPk(ctx.from.id)
    let userEnemy = rand(0,10)
    console.log(userEnemy)
    switch(userEnemy){
        case 4: case 5: case 6: case 7:
            userEnemy = rarecars.random()
            break;
        default:
            userEnemy = simplecars.random()
            break;
    }
    userEnemy.health = rand(10, 100)
    //ctx.deleteMessage()
    let enemyRate = (userEnemy.speed + userEnemy.acceleration + userEnemy.control) + userEnemy.health
    let userRate = (property.car1.speed + property.car1.acceleration + property.car1.control) + property.car1.health
    await ctx.sendPhoto(userEnemy.image, { caption: `
    Автомобиль противника:
     ${userEnemy.name} | ${enemyRate}
            Состояние: ${userEnemy.health}%
            Скорость: ${userEnemy.speed}
            Ускорение: ${userEnemy.acceleration}
            Управляемость: ${userEnemy.control}
    

    Ваш автомобиль:
    ${property.car1.name} | ${userRate}
            Состояние: ${property.car1.health}%
            Скорость: ${property.car1.speed}
            Ускорение: ${property.car1.acceleration}
            Управляемость: ${property.car1.control}
    `})

let winner = "Nobody"
let winCheck = rand(0, 100)
console.log(winCheck)
    if((userRate - enemyRate) > 10) {
        winner = user.username
    }else{
        if(winCheck >= 50){
            winner = userEnemy.name
        }else{
            winner = user.username
        }
    }

    let carDamage = rand(1, 10)
    property.car1.health = 5
    const updateProperty = {
        car1: sequelize.fn('jsonb_set', 'car1', 'health', sequelize.literal(`car1->'health' - ${carDamage}`)),
      };
      
      await property.update(updateProperty);
    property.save()
    return ctx.reply(`
    🏁 Результаты заезда:
    ${userEnemy.name} 
______🚗___________________

${user.username} 
🚗_________________________

📣 Победитель ${winner}
Выигрыш: 50.000🔶

💬 Отчет:
${userEnemy.name}
Состояние: -${carDamage}%

${property.car1.name} 
Состояние: -8%
    `)
}