using Brizco.Domain.Entities.Tasks;

namespace Brizco.Repository.Handlers.Tasks;

public class GetActivitiesQueryHandler(IRepositoryWrapper repositoryWrapper, ICurrentUserService currentUserService) : IRequestHandler<GetTasksQuery, List<TaskSDto>>
{
    public async Task<List<TaskSDto>> Handle(GetTasksQuery request, CancellationToken cancellationToken)
    {
        if (currentUserService.ComplexId == null)
            throw new AppException("ComplexId is null", ApiResultStatusCode.NotFound);
        if (!Guid.TryParse(currentUserService.ComplexId, out Guid complexId))
            throw new AppException("ComplexId is wrong", ApiResultStatusCode.NotFound);
        var query = repositoryWrapper.SetRepository<Domain.Entities.Tasks.Task>().TableNoTracking
            .Where(t => t.ComplexId == complexId && t.IsActivity == false);

        if (request.ShiftId != null)
            query = from taskShift in repositoryWrapper.SetRepository<TaskShift>().TableNoTracking
                where taskShift.ShiftId == request.ShiftId
                join task in query on taskShift.TaskId equals task.Id
                select task;

        query = query.Distinct();

        var tasks = await query
            .OrderByDescending(s => s.CreatedAt)
            .Skip(request.Page * 15).Take(15)
            .Select(TaskMapper.ProjectToSDto)
            .ToListAsync(cancellationToken);

        return tasks;
    }
}