using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PARR.Core.Repositories.Interfaces.TaskRepositories;
using PARR.DAL.Context;
using PARR.DAL.Repositories.Base;
using PARR.Domain.Constants;
using PARR.Domain.Entities.TaskEntities;
using PARR.Domain.Enums;

namespace PARR.DAL.Repositories.TaskRepositories
{
    internal class TaskRepository : BaseRepository<TaskItem>, ITaskRepository
    {
        public TaskRepository(DataContext dataContext, ILogger<TaskRepository> logger) : base(logger, dataContext) { }

        public async Task<int> TaskCaptureAsync(Guid taskId)
        {
            //var sql = $@"
            //            UPDATE ""{DatabaseSchemas.Task}"".""Tasks""
            //            SET ""{nameof(TaskItem.StatusCode)}"" = {(int)TaskItemStatusEnum.Processing},
            //                ""{nameof(TaskItem.DateModified)}"" = {{0}}
            //            WHERE ""{nameof(TaskItem.Id)}"" = {{1}}
            //              AND ""{nameof(TaskItem.StatusCode)}"" = {(int)TaskItemStatusEnum.Pending}";

            //var affectedRows = await EntityContext.Database.ExecuteSqlRawAsync(sql, DateTimeOffset.UtcNow, taskId);

            //return affectedRows;

            return await EntityContext.Tasks.Where(t => t.Id == taskId && t.StatusCode == TaskItemStatusEnum.Pending)
                                            .ExecuteUpdateAsync(t=>t
                                                .SetProperty(p=>p.StatusCode, TaskItemStatusEnum.Processing)
                                                .SetProperty(p => p.DateModified, DateTimeOffset.UtcNow)
                                            );
        }


        public async Task<int> UpdateProgressAsync(Guid taskId, int percent)
        {
            // Валидация на уровне БД
            if (percent < 0) 
                percent = 0;

            if (percent > 100) 
                percent = 100;

            //return await EntityContext.Database.ExecuteSqlInterpolatedAsync($@"
            //                                            UPDATE ""{DatabaseSchemas.Task}"".""Tasks"" 
            //                                            SET ""{nameof(TaskItem.ProgressPercent)}"" = {percent},
            //                                                ""{nameof(TaskItem.DateModified)}"" = {DateTimeOffset.UtcNow}
            //                                            WHERE ""{nameof(TaskItem.Id)}"" = {taskId}");
            
            // Атомарное обновление
            return await EntityContext.Tasks.Where(t => t.Id == taskId).ExecuteUpdateAsync(t => t
                                                        .SetProperty(x => x.ProgressPercent, percent)
                                                        //.SetProperty(x => x.DateModified, DateTimeOffset.UtcNow)
                                                    );
        }

    }
}
