package com.micer.easyball.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.micer.easyball.mapper.GameImageMapper;
import com.micer.easyball.mapper.GameMapper;
import com.micer.easyball.mapper.PlayerLastClubMapper;
import com.micer.easyball.pojo.Game;
import com.micer.easyball.pojo.GameImage;
import com.micer.easyball.pojo.PlayerLastClub;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class FileAccessService {

    @Autowired
    private GameMapper gameMapper;

    @Autowired
    private GameImageMapper gameImageMapper;

    @Autowired
    private PlayerLastClubMapper playerLastClubMapper;

    /**
     * 校验当前用户是否有权访问指定文件
     */
    public boolean canAccessFile(String userId, String fileName) {
        // 1. 路径格式校验：必须是 /image/{gameId}/文件名
        if (fileName == null || !fileName.startsWith("/image/")) {
            return false;
        }

        // 2. 禁止路径遍历
        if (fileName.contains("..") || fileName.contains("\\")) {
            return false;
        }

        // 3. 提取 gameId
        String[] parts = fileName.split("/");
        if (parts.length < 4) {
            return false;
        }
        String gameId = parts[2];

        // 4. 校验比赛归属：game.our_team_id = 当前用户 last_club_id
        Game game = gameMapper.selectById(gameId);
        if (game == null) {
            return false;
        }

        PlayerLastClub playerLastClub = playerLastClubMapper.selectOne(
            new QueryWrapper<PlayerLastClub>().eq("player_id", userId)
        );
        if (playerLastClub == null) {
            return false;
        }

        String currentClubId = playerLastClub.getLastClubId();
        if (!game.getOurTeamId().equals(currentClubId)) {
            return false;  // 比赛不属于当前用户俱乐部
        }

        // 5. 校验数据库记录：game_image 中存在该路径
        GameImage gameImage = gameImageMapper.selectOne(
            new QueryWrapper<GameImage>()
                .eq("game_id", gameId)
                .eq("image_path", fileName)
        );

        return gameImage != null;
    }

    /**
     * 校验当前用户是否有权针对指定比赛进行管理操作（上传/删除全部图片等）
     */
    public boolean canAccessGame(String userId, String gameId) {
        if (gameId == null) return false;
        Game game = gameMapper.selectById(gameId);
        if (game == null) return false;
        PlayerLastClub playerLastClub = playerLastClubMapper.selectOne(
            new QueryWrapper<PlayerLastClub>().eq("player_id", userId)
        );
        if (playerLastClub == null) return false;
        return game.getOurTeamId().equals(playerLastClub.getLastClubId());
    }

}
