package com.example.demo01.service.impl;

import com.example.demo01.controller.BattleResult;
import com.example.demo01.entity.Monster;
import com.example.demo01.entity.Player;
import com.example.demo01.mapper.MonsterMapper;
import com.example.demo01.mapper.PlayerMapper;
import com.example.demo01.service.BattleService;
import com.example.demo01.service.PlayerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class BattleServiceImpl implements BattleService {

    @Autowired
    private PlayerMapper playerMapper;
    @Autowired
    private MonsterMapper monsterMapper;
    @Autowired
    private PlayerService playerService;

    @Override
    @Transactional
    public BattleResult attack(Long playerId, Long monsterId) {
        Player player = playerMapper.selectById(playerId);
        Monster monster = monsterMapper.selectById(monsterId);

        StringBuilder log = new StringBuilder();

        // 1. 玩家攻击怪物
        // 伤害公式：攻击力 - 防御力（最小为1）
        int damageToMonster = Math.max(1, player.getAtk() - monster.getDef());
        monster.setHp(Math.max(0, monster.getHp() - damageToMonster));
        log.append(String.format("你攻击了 %s，造成了 %d 点伤害。 ", monster.getName(), damageToMonster));

        // 2. 检查怪物是否死亡
        if (!monster.isAlive()) {
            log.append(String.format("%s 倒下了！你获得了 %d 经验。", monster.getName(), monster.getExpReward()));
            // 结算奖励
            playerService.addRewards(playerId, monster.getExpReward(), monster.getGoldReward());
            // 从房间移除怪物（可选逻辑：更新Room表或者标记Monster已死）
            monsterMapper.deleteById(monsterId);

            return BattleResult.builder()
                    .log(log.toString()).monsterHp(0).playerHp(player.getHp())
                    .monsterDead(true).rewardsExp(monster.getExpReward()).build();
        }

        // 3. 怪物反击（如果还没死）
        int damageToPlayer = Math.max(1, monster.getAtk() - 5); // 假设玩家基础防御5
        player.setHp(Math.max(0, player.getHp() - damageToPlayer));
        playerMapper.updateById(player); // 更新玩家血量
        monsterMapper.updateById(monster); // 更新怪物血量

        log.append(String.format("%s 发起反击，你受到了 %d 点伤害。", monster.getName(), damageToPlayer));

        return BattleResult.builder()
                .log(log.toString())
                .playerHp(player.getHp())
                .monsterHp(monster.getHp())
                .playerDead(player.getHp() <= 0)
                .build();
    }
}
