namespace Brizco.Core.EntityServices;

public class ShiftPlanService(IMediator mediator, IActivityService activityService, IRepositoryWrapper repositoryWrapper) : IShiftPlanService
{
    public async Task ChangeShiftPlanTaskStatusAsync(Guid shiftPlanId, bool isChangeToShift, bool isDisable)
    {
        var shiftPlan = await mediator.Send(new GetShiftPlanQuery(shiftPlanId));

    }

    public async Task<bool> CreateAsync(CreateShiftPlanCommand createShiftPlanCommand, CancellationToken cancellationToken)
    {
        var shiftPlan = await mediator.Send(createShiftPlanCommand, cancellationToken);
        await activityService.CreateActivitiesByShiftPlan(shiftPlan.Id, cancellationToken);
        await mediator.Send(new CreateShiftPlanNotificationsCommand(shiftPlan.Id,true), cancellationToken);
        return true;
    }

    public async Task<bool> UpdateAsync(UpdateShiftPlanCommand updateShiftPlanCommand, CancellationToken cancellationToken)
    {
         await mediator.Send(updateShiftPlanCommand, cancellationToken);
         await activityService.UpdateActivitiesByShiftPlan(updateShiftPlanCommand.Id, cancellationToken);
         return true;
    }

    public async Task<bool> CompleteShiftPlanAsync(Guid id, CompleteShiftPlanRequestDto requestDtos, CancellationToken cancellationToken)
    {
        var shiftPlan = await repositoryWrapper.SetRepository<ShiftPlan>()
            .TableNoTracking.FirstOrDefaultAsync(s => s.Id == id, cancellationToken);
        if (shiftPlan == null)
            throw new AppException("Shift plan not found", ApiResultStatusCode.NotFound);

        shiftPlan.CompletePlan(requestDtos.CompleteDescription,requestDtos.CompletePercent);
        repositoryWrapper.SetRepository<ShiftPlan>().Update(shiftPlan);
        await repositoryWrapper.SaveChangesAsync(cancellationToken);
        await activityService.CompleteActivitiesAsync(requestDtos.CompleteActivities, cancellationToken);

        var shiftPlanUsers = await repositoryWrapper.SetRepository<ShiftPlanUser>()
            .TableNoTracking.Where(s => s.ShiftPlanId == id)
            .Select(ShiftPlanUserMapper.ProjectToSDto)
            .ToListAsync(cancellationToken);
        
        foreach (var shiftPlanUser in shiftPlanUsers)
        {
            var message = $"{shiftPlanUser.UserFullName}";
        }

        return true;
    }
}