using System.Threading.Channels;
using ErsatzTV.Application.Playouts;
using ErsatzTV.Core;
using ErsatzTV.Core.Domain.Scheduling;
using ErsatzTV.Core.Scheduling;
using ErsatzTV.Infrastructure.Data;
using ErsatzTV.Infrastructure.Extensions;
using Microsoft.EntityFrameworkCore;

namespace ErsatzTV.Application.Scheduling;

public class ReplaceDecoTemplateItemsHandler(
    IDbContextFactory<TvContext> dbContextFactory,
    ChannelWriter<IBackgroundServiceRequest> channel)
    : IRequestHandler<ReplaceDecoTemplateItems, Either<BaseError, List<DecoTemplateItemViewModel>>>
{
    public async Task<Either<BaseError, List<DecoTemplateItemViewModel>>> Handle(
        ReplaceDecoTemplateItems request,
        CancellationToken cancellationToken)
    {
        await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
        Validation<BaseError, DecoTemplate> validation = await Validate(dbContext, request, cancellationToken);

        // Introduce the optimistic-concurrency check as a standalone Either AFTER the validation
        // pipeline (never via Apply) so a PreconditionFailedError survives to a 412 and is not
        // flattened to a generic 422 by Join() (issue #253 / api-conventions §7a).
        Either<BaseError, DecoTemplate> validated = LanguageExtensions.ToEither(validation)
            .Bind(decoTemplate => decoTemplate.CheckVersion(request.ExpectedVersions));

        return await validated.Match(
            Right: decoTemplate => Persist(dbContext, request, decoTemplate, cancellationToken),
            Left: error => Task.FromResult<Either<BaseError, List<DecoTemplateItemViewModel>>>(error));
    }

    private async Task<Either<BaseError, List<DecoTemplateItemViewModel>>> Persist(
        TvContext dbContext,
        ReplaceDecoTemplateItems request,
        DecoTemplate decoTemplate,
        CancellationToken cancellationToken)
    {
        decoTemplate.Name = request.Name;
        decoTemplate.DateUpdated = DateTime.UtcNow;

        dbContext.RemoveRange(decoTemplate.Items);

        decoTemplate.Items = request.Items.Map(i => BuildItem(decoTemplate, i)).ToList();

        // Unconditional bump: EF emits the root UPDATE only when a scalar actually differs, so a
        // same-value/no-op save would otherwise write no root row and neither fire the concurrency
        // token nor rotate other clients' ETags. Bumping guarantees both on every save (issue #253).
        decoTemplate.Version++;

        // Save through the guard so an EF concurrency failure (a racing writer won between our load
        // and save) maps to 412 rather than surfacing as a 500.
        Either<BaseError, Unit> saved = await dbContext.SaveChangesWithConcurrencyGuard(cancellationToken);
        return await saved.Match(
            Right: async _ =>
            {
                // Deco/break/default-filler content is only (re)applied during a Reset build (a Continue keeps
                // the frozen DecoDefault filler items), and BlockKey change-detection has no deco dimension, so
                // nothing self-heals a deco-template edit — the editor returned 200 but built filler stayed
                // stale until a manual Reset (#251). Enqueue a Reset for every playout that references this
                // deco template. This whole post-commit invalidation runs with CancellationToken.None (audit
                // #22 policy): once the edit is committed, a late request cancellation must not be able to
                // abort the affected-playout query OR the enqueue and leave content stale. Only runs after a
                // successful save (issue #253) — a 412/422 must not enqueue a Reset for content that was never
                // persisted.
                List<int> playoutIds = await dbContext.PlayoutTemplates
                    .Where(pt => pt.DecoTemplateId == decoTemplate.Id)
                    .Select(pt => pt.PlayoutId)
                    .Distinct()
                    .ToListAsync(CancellationToken.None);

                foreach (int playoutId in playoutIds)
                {
                    await channel.WriteAsync(
                        new BuildPlayout(playoutId, PlayoutBuildMode.Reset),
                        CancellationToken.None);
                }

                await dbContext.Entry(decoTemplate)
                    .Collection(t => t.Items)
                    .Query()
                    .Include(i => i.Deco)
                    .LoadAsync(cancellationToken);

                return Right<BaseError, List<DecoTemplateItemViewModel>>(
                    decoTemplate.Items.Map(Mapper.ProjectToViewModel).ToList());
            },
            Left: error => Task.FromResult(Left<BaseError, List<DecoTemplateItemViewModel>>(error)));
    }

    private static DecoTemplateItem BuildItem(DecoTemplate decoTemplate, ReplaceDecoTemplateItem item) =>
        new()
        {
            DecoTemplateId = decoTemplate.Id,
            DecoId = item.DecoId,
            StartTime = item.StartTime,
            EndTime = item.EndTime
        };

    private static Task<Validation<BaseError, DecoTemplate>> Validate(
        TvContext dbContext,
        ReplaceDecoTemplateItems request,
        CancellationToken cancellationToken) =>
        DecoTemplateMustExist(dbContext, request.DecoTemplateId, cancellationToken)
            .BindT(decoTemplate => DecoTemplateNameMustBeValid(dbContext, decoTemplate, request))
            .BindT(decoTemplate => DecoTemplateItemsMustBeValid(dbContext, decoTemplate, request));

    // Hardening (deliberate deviation from the original handler): rather than silently filtering out
    // invalid items (unknown DecoId, StartTime >= EndTime, or overlapping ranges) - the same silent-drop
    // and silent-overlap bug class fixed for ReplaceTemplateItemsHandler in #144 S2 - reject the whole
    // request with a 422 so the caller knows exactly what is wrong. EndTime == TimeSpan.Zero means
    // "end of day" (24:00) and is treated as such for both the ordering and overlap checks.
    private static async Task<Validation<BaseError, DecoTemplate>> DecoTemplateItemsMustBeValid(
        TvContext dbContext,
        DecoTemplate decoTemplate,
        ReplaceDecoTemplateItems request)
    {
        var allDecoIds = request.Items.Map(i => i.DecoId).Distinct().ToList();

        Dictionary<int, Deco> allDecos = await dbContext.Decos
            .AsNoTracking()
            .Filter(d => allDecoIds.Contains(d.Id))
            .ToListAsync()
            .Map(list => list.ToDictionary(d => d.Id, d => d));

        var missingDecoIds = allDecoIds.Filter(id => !allDecos.ContainsKey(id)).ToList();
        if (missingDecoIds.Count > 0)
        {
            return BaseError.New($"[DecoId] {missingDecoIds.Head()} does not exist.");
        }

        var itemsWithEffectiveEnd = request.Items
            .Map(i => new DecoTemplateItemRange(
                i.DecoId,
                i.StartTime,
                i.EndTime,
                i.EndTime == TimeSpan.Zero ? TimeSpan.FromHours(24) : i.EndTime))
            .ToList();

        foreach (DecoTemplateItemRange item in itemsWithEffectiveEnd)
        {
            if (item.StartTime < TimeSpan.Zero || item.StartTime >= TimeSpan.FromHours(24) ||
                item.EndTime < TimeSpan.Zero || item.EndTime > TimeSpan.FromHours(24))
            {
                return BaseError.New(
                    $"Deco from {item.StartTime} to {item.EndTime} must be within a single day (00:00 to 24:00)");
            }

            if (item.StartTime >= item.EffectiveEndTime)
            {
                return BaseError.New(
                    $"Deco from {item.StartTime} to {item.EndTime} must start before it ends");
            }
        }

        foreach (DecoTemplateItemRange item in itemsWithEffectiveEnd)
        {
            foreach (DecoTemplateItemRange otherItem in itemsWithEffectiveEnd)
            {
                if (item == otherItem)
                {
                    continue;
                }

                if (item.StartTime < otherItem.EffectiveEndTime && otherItem.StartTime < item.EffectiveEndTime)
                {
                    return BaseError.New(
                        $"Deco from {item.StartTime} to {item.EndTime} intersects deco from {otherItem.StartTime} to {otherItem.EndTime}");
                }
            }
        }

        return decoTemplate;
    }

    private sealed record DecoTemplateItemRange(int DecoId, TimeSpan StartTime, TimeSpan EndTime, TimeSpan EffectiveEndTime);

    private static Task<Validation<BaseError, DecoTemplate>> DecoTemplateMustExist(
        TvContext dbContext,
        int decoTemplateId,
        CancellationToken cancellationToken) =>
        dbContext.DecoTemplates
            .Include(b => b.Items)
            .SelectOneAsync(b => b.Id, b => b.Id == decoTemplateId, cancellationToken)
            .Map(o => o.ToValidation<BaseError>("[DecoTemplateId] does not exist."));

    private static async Task<Validation<BaseError, DecoTemplate>> DecoTemplateNameMustBeValid(
        TvContext dbContext,
        DecoTemplate decoTemplate,
        ReplaceDecoTemplateItems request)
    {
        if (string.IsNullOrWhiteSpace(request.Name) || request.Name.Length > 50)
        {
            return BaseError.New($"Deco template name \"{request.Name}\" is invalid");
        }

        Option<DecoTemplate> maybeExisting = await dbContext.DecoTemplates
            .AsNoTracking()
            .FirstOrDefaultAsync(d =>
                d.Id != request.DecoTemplateId && d.DecoTemplateGroupId == request.DecoTemplateGroupId &&
                d.Name == request.Name)
            .Map(Optional);

        return maybeExisting.IsSome
            ? BaseError.New($"A deco template named \"{request.Name}\" already exists in that deco template group")
            : Success<BaseError, DecoTemplate>(decoTemplate);
    }
}
