using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using PARR.BLL.Domain.Mq;
using PARR.Common.Domain;
using PARR.Constants;
using PARR.DAL.Contracts;
using PARR.DAL.Models;
using PARR.DAL.Services.Interfaces;
using PARR.DAL.Services.Interfaces.Job;
using PARR.TemplateMatcher.Services.Interfaces;

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 ITemplateService templateService;
    private readonly IJobService jobService;
    private readonly ITemplateNameNormalizer namenormalizer;
    private readonly ITemplateUpdaterMqSender sender;
    private readonly SettingsFromDb settingsFromDb;

    public TemplateDeactivator(
        ILogger<TemplateDeactivator> logger,
        ITemplateService templateService,
        IJobService jobService,
        ITemplateNameNormalizer namenormalizer,
        ITemplateUpdaterMqSender sender,
        SettingsFromDb settingsFromDb
        )
    {
        this.logger = logger;
        this.templateService = templateService;
        this.jobService = jobService;
        this.namenormalizer = namenormalizer;
        this.sender = sender;
        this.settingsFromDb = settingsFromDb;
    }

    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;
        }

        // === Создаём временный 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 TemplateUpdaterMq
        {
            TemplateId = template.Id,
            JobId = unusedJob.Id,
            UnitId = template.UnitId,
            Name = expectedName + "_" + DateTimeOffset.UtcNow.ToUnixTimeSeconds(),
            IsActiveTemplate = DefaultUnusedTemplateState,
            IsActiveSchedule = DefaultUnusedScheduleState,
            LastRun = template.LastRun,
            NextRun = template.NextRun,
            Index = template.Index,
            StatusTypeId = TemplateStatusTypeEnum.Unused,
            Initiator = initiator,
            UnitsInTemplate = new List<Guid>()
        };

        await sender.SendTemplateUpdateMessageAsync(updateRequest);
        return true;
    }
}