using Application.Abstractions.Data;
using Application.Abstractions.Forum;
using Domain.Entities.Forum.Boards;
using Domain.Entities.Members;
using Microsoft.EntityFrameworkCore;

namespace Infrastructure.Forum;

public sealed class BoardPermissionService(IAppDbContext db) : IBoardPermissionService
{
    public async Task<short> GetMemberPermissionLevelAsync(Member member, int boardID, CancellationToken ct)
    {
        // 최고관리자인가?
        if (member.IsAdmin)
        {
            return 1000;
        }

        // 게시판 매니저인가?
        var isManager = await db.BoardManager.AsNoTracking().AnyAsync(x => x.BoardID == boardID && x.MemberID == member.ID, ct);
        if (isManager)
        {
            return 99;
        }

        // 회원 등급이 높은가 ?
        if (member.MemberGradeID.HasValue)
        {
            var grade = await db.MemberGrade.AsNoTracking().FirstOrDefaultAsync(x => x.ID == member.MemberGradeID.Value, ct);
            if (grade != null)
            {
                if (!grade.IsActive)
                {
                    return -2; // 비활성 등급은 차단
                }
            }

            return grade?.Order ?? 0;
        }

        return 0;
    }

    public async Task<bool> HasPermissionAsync(Member member, int boardID, short requiredPermission, CancellationToken ct)
    {
        // 비회원 허용
        if (requiredPermission <= -1)
        {
            return true;
        }

        var level = await GetMemberPermissionLevelAsync(member, boardID, ct);
        return level >= requiredPermission;
    }

    public async Task<BoardManager?> GetBoardManagerAsync(int boardID, int memberID, CancellationToken ct)
    {
        return await db.BoardManager.AsNoTracking().FirstOrDefaultAsync(x => x.BoardID == boardID && x.MemberID == memberID, ct);
    }
}