using IWS5.Core.Enums;
using IWS5.Core.Models.Request;
using IWS5.DatabaseAccess.Interfaces;
using IWS5.DatabaseAccess.IwsDataContext;
using IWS5.DatabaseAccess.IwsDataModels;
using Microsoft.EntityFrameworkCore;

namespace IWS5.DatabaseAccess.Repositories;

public class ButtonRepository(GreenfieldPd2015Context context)
    : IWSRepository<Atbutton>(context), IButtonRepository
{
    public async Task<(List<Atbutton> Buttons, List<Atright> Rights)> GetButtonsAndRights(ButtonRequest buttonRequest)
    {
        var query = from user in context.Atusers
            where user.UserName == buttonRequest.UserName
            from parent in user.Parents
            from right in parent.Atrights
            where right.ObjectType == (int)ObjectType.Button
            join button in context.Atbuttons on right.ObjectGuid equals button.ObjectId
            where button.QueueId == buttonRequest.QueueId
            select new { button, right };

        var result = await query.ToListAsync();

        var buttons = result.Select(r => r.button).GroupBy(b => b.ObjectId).Select(g => g.First()).ToList();
        var rights = result.Select(r => r.right).Distinct().ToList();

        return (buttons, rights);
    }
}