using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PARR.Core.Repositories.Interfaces.JobRepositories;
using PARR.TemplateMatcher.Services.SimpleSync;

namespace PARR.TemplateMatcher.Services.Implementations.SimpleSync;

internal class LoadJobStage : ISimpleSyncStage
{
    private readonly IJobRepository _jobRepository;
    private readonly ILogger<LoadJobStage> _logger;

    public string StageName => "Загрузка Job";

    public LoadJobStage(IJobRepository jobRepository, ILogger<LoadJobStage> logger)
    {
        _jobRepository = jobRepository;
        _logger = logger;
    }

    public async Task<SimpleSyncContext> ExecuteAsync(SimpleSyncContext context, CancellationToken ct = default)
    {
        var job = await _jobRepository.Get()
            .AsNoTracking()
            .AsSplitQuery()
            .Include(j => j.AutoControl)
            .Include(j => j.Tnk)
            .Include(j => j.Group).ThenInclude(g => g!.GroupType)
            .Include(j => j.AutoControl)
            .Include(j => j.UnitFilters).ThenInclude(uf => uf.RelationshipFilters)
            .FirstOrDefaultAsync(j => j.Id == context.JobId, ct);

        if (job == null)
            throw new InvalidOperationException($"Job '{context.JobId}' не найден");

        context.Job = job;
        context.JobName = job.Name;

        _logger.LogDebug("Job '{JobName}' ({JobId}) загружен", job.Name, job.Id);

        return context;
    }
}