using Microsoft.Extensions.Logging;
using PARR.Domain.Common.Rabbit.Messages.TemplateMatching;
using PARR.TemplateMatcher.Models;
using PARR.TemplateMatcher.Services.Interfaces;

namespace PARR.TemplateMatcher.Services.Implementations
{
    internal class TemplateAllocationService : ITemplateAllocationService
    {
        private readonly ILogger<TemplateAllocationService> logger;
        private readonly ITemplateReuser reuser;
        private readonly ITemplateMqPublisher publisher;

        public TemplateAllocationService(
            ILogger<TemplateAllocationService> logger,
            ITemplateReuser reuser,
            ITemplateMqPublisher publisher)
        {
            this.logger = logger;
            this.reuser = reuser;
            this.publisher = publisher;
        }

        public async Task AllocateAsync(TemplateAllocationRequest request, CancellationToken ct = default)
        {
            // Пробуем переиспользовать
            bool reused = await reuser.TryReuseAsync(
                request.TargetJob,
                request.TargetUnitId,
                request.TargetUnit,
                request.Index,
                request.UnitsInTemplate,
                request.IsActiveTemplate,
                request.IsActiveSchedule,
                request.Initiator,
                ct);

            if (!reused)
            {
                logger.LogDebug("Переиспользование не удалось. Запрос на создание шаблона для Job {JobId}, Unit {UnitId}, Index {Index}.",
                    request.TargetJob.Id, request.TargetUnitId, request.Index);

                var createMessage = new TemplateGeneratorMessage
                {
                    JobId = request.TargetJob.Id,
                    UnitId = request.TargetUnitId,
                    Index = request.Index,
                    UnitsInTemplate = request.UnitsInTemplate ?? new List<UnitInTemplateMessage>(),
                    IsActiveTemplate = request.IsActiveTemplate,
                    IsActiveSchedule = request.IsActiveSchedule,
                    HistoryInitiator = request.Initiator
                };

                await publisher.PublishCreateAsync(createMessage, ct);
            }
        }
    }
}
