package com.pandoli365.bibimbap.security;

import com.pandoli365.bibimbap.mapper.JamEntriesMapper;
import com.pandoli365.bibimbap.mapper.JamJudgesMapper;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;

/**
 * 잼 스코프 게이트 — 전역 PermissionGate(권한 키 축)와 별도 축(잼 리소스 역할 축).
 * 잼 역할은 요청당 jam_judges 직접 조회로 판정한다(캐시·epoch 없음 — 지정/해제 다음 요청 즉시 반영).
 */
@Component
public class JamRoleGate {

    private final JamJudgesMapper jamJudgesMapper;
    private final JamEntriesMapper jamEntriesMapper;

    public JamRoleGate(JamJudgesMapper jamJudgesMapper, JamEntriesMapper jamEntriesMapper) {
        this.jamJudgesMapper = jamJudgesMapper;
        this.jamEntriesMapper = jamEntriesMapper;
    }

    public boolean isJudge(HttpSession session, long jamId) {
        Long userId = sessionUserId(session);
        if (userId == null) {
            return false;
        }
        return jamJudgesMapper.exists(jamId, userId);
    }

    public boolean isOwnEntry(long jamId, long gameId, long judgeUserId) {
        return jamEntriesMapper.isOwnEntry(jamId, gameId, judgeUserId);
    }

    private Long sessionUserId(HttpSession session) {
        if (session == null) {
            return null;
        }
        Object attr = session.getAttribute("userId");
        if (attr instanceof Number number) {
            return number.longValue();
        }
        if (attr instanceof String s) {
            try {
                return Long.parseLong(s);
            } catch (NumberFormatException e) {
                return null;
            }
        }
        return null;
    }
}
