using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using PARR.Core.Repositories.Interfaces;
using PARR.Core.Repositories.Interfaces.Job;
using PARR.Domain.Common.Rabbit.Messages.TemplateMatching;
using PARR.Domain.Entities;
using PARR.Domain.Entities.Base.History;
using PARR.Domain.Entities.Job;
using PARR.Domain.Enums;
using PARR.Domain.Settings;
using PARR.TemplateMatcher.Services.Interfaces;
using PARR.TemplateMatcher.Settings;

namespace PARR.TemplateMatcher.Services.Implementations;

internal class TemplateDeactivator : ITemplateDeactivator
{
    private const bool DefaultUnusedTemplateState = false;
    private const bool DefaultUnusedScheduleState = false;

    private readonly ILogger<TemplateDeactivator> logger;
    private readonly ITemplateRepository templateService;
    private readonly IJobRepository jobService;
    private readonly ITemplateNameNormalizer namenormalizer;
    private readonly ITemplateMqPublisher templateMqPublisher;
    private readonly SettingsFromDb settingsFromDb;
    private readonly IOptions<TemplateSettings> templateSettings;

    public TemplateDeactivator(
        ILogger<TemplateDeactivator> logger,
        ITemplateRepository templateService,
        IJobRepository jobService,
        ITemplateNameNormalizer namenormalizer,
        ITemplateMqPublisher templateMqPublisher,
        SettingsFromDb settingsFromDb,
        IOptions<TemplateSettings> templateSettings
        )
    {
        this.logger = logger;
        this.templateService = templateService;
        this.jobService = jobService;
        this.namenormalizer = namenormalizer;
        this.templateMqPublisher = templateMqPublisher;
        this.settingsFromDb = settingsFromDb;
        this.templateSettings = templateSettings;
    }

    public async Task<bool> DeactivateTemplateAsync(Template template, HistoryInitiator initiator)
    {
        if (template.StatusTypeId == TemplateStatusTypeEnum.Updating)
            return true;

        if (template.StatusTypeId == TemplateStatusTypeEnum.Unused)
        {
            logger.LogDebug("Шаблон {TemplateId} уже неактивен (Unused), пропускаем деактивацию.", template.Id);
            return true;
        }

        logger.LogInformation("Шаблон {TemplateId} (UnitId {UnitId}) → деактивация.",
            template.Id, template.UnitId);

        template.StatusTypeId = TemplateStatusTypeEnum.Updating;
        template.DateModified = DateTimeOffset.UtcNow;

        if (!await templateService.CommitAsync(initiator))
        {
            logger.LogError("Не удалось перевести шаблон {TemplateId} в Updating.", template.Id);
            return false;
        }

        var unusedJob = await jobService.Get()
            .AsNoTracking()
            .Include(j => j.Tnk)
            .Include(j => j.Group)
                .ThenInclude(g => g!.GroupType)
            .FirstOrDefaultAsync(j => j.Id == settingsFromDb.JobIdForUnusedTemplates);


        if (unusedJob == null)
        {
            logger.LogError("Job для деактивированных шаблонов не найден.");
            return false;
        }

        unusedJob.TemplateNameMask = templateSettings.Value.UnusedTemplateNameMask;

        // === Создаём временный Template для нормализации имени ===
        var tempTemplateForName = new Template
        {
            Id = template.Id,
            Name = template.Name,
            JobId = unusedJob.Id,
            UnitId = template.UnitId,
            Index = template.Index,
            Job = unusedJob,
            Unit = template.Unit,
            UnitsInTemplate = new List<UnitsInTemplate>()
        };

        var expectedName = await namenormalizer.GetNormalizedTemplateNameAsync(tempTemplateForName);

        var updateRequest = new TemplateUpdaterMessage
        {
            TemplateId = template.Id,
            JobId = unusedJob.Id,
            UnitId = template.UnitId,
            Name = expectedName,
            IsActiveTemplate = DefaultUnusedTemplateState,
            IsActiveSchedule = DefaultUnusedScheduleState,
            IsNew = false,
            Index = template.Index,
            StatusTypeId = TemplateStatusTypeEnum.Unused,
            Initiator = initiator,
            UnitsInTemplate = new List<UnitInTemplateMessage>()
        };

        await templateMqPublisher.PublishUpdateAsync(updateRequest);
        return true;
    }
}