using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using SolutionErp.Application.Common.Interfaces;
using SolutionErp.Application.Notifications;
using SolutionErp.Application.Office;
using SolutionErp.Domain.Notifications;
using SolutionErp.Domain.Office;

namespace SolutionErp.Infrastructure.HostedServices;

// P11-D (Mig 46 — Phase 11 Wave 2) — SLA timer cho IT helpdesk ticket.
// Mirror pattern SlaExpiryJob (HĐ) NHƯNG KHÔNG auto-transition status — ticket
// chỉ CẢNH BÁO (warning ≤20% window + breach quá hạn) gửi notification cho assignee.
// Status flow (Open → InProgress → Resolved → Closed) do IT staff điều khiển tay.
// Chạy mỗi 15 phút, warmup 30s tránh race DbInitializer migrate.
// SLA window theo Priority = source-of-truth CreateItTicketHandler.SlaWindow (shared).
public class ItTicketSlaJob : BackgroundService
{
    private readonly IServiceProvider _sp;
    private readonly ILogger<ItTicketSlaJob> _logger;
    private static readonly TimeSpan Interval = TimeSpan.FromMinutes(15);

    public ItTicketSlaJob(IServiceProvider sp, ILogger<ItTicketSlaJob> logger)
    {
        _sp = sp;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);

        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                await ProcessAsync(stoppingToken);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "ItTicketSlaJob iteration failed");
            }
            await Task.Delay(Interval, stoppingToken);
        }
    }

    private async Task ProcessAsync(CancellationToken ct)
    {
        await using var scope = _sp.CreateAsyncScope();
        var db = scope.ServiceProvider.GetRequiredService<IApplicationDbContext>();
        var dateTime = scope.ServiceProvider.GetRequiredService<IDateTime>();
        var notifications = scope.ServiceProvider.GetRequiredService<INotificationService>();

        var now = dateTime.UtcNow;

        await ProcessBreachesAsync(db, notifications, now, ct);
        await ProcessWarningsAsync(db, notifications, now, ct);
    }

    // Breach: ticket quá hạn SLA mà chưa đánh dấu breach + còn open (chưa Resolved/Closed).
    // Set SlaBreached=true + notify assignee (nếu có). Idempotent qua !SlaBreached guard.
    private async Task ProcessBreachesAsync(
        IApplicationDbContext db, INotificationService notifications,
        DateTime now, CancellationToken ct)
    {
        var breached = await db.ItTickets
            .Where(t => t.SlaDueAt != null && t.SlaDueAt < now
                && !t.SlaBreached
                && t.Status != ItTicketStatus.Resolved && t.Status != ItTicketStatus.Closed
                && !t.IsDeleted)
            .ToListAsync(ct);

        if (breached.Count == 0) return;

        foreach (var t in breached)
        {
            if (t.AssignedToUserId is Guid assignee)
            {
                await notifications.NotifyAsync(
                    assignee,
                    NotificationType.SlaWarning,
                    title: $"⚠ Ticket {t.MaTicket ?? t.Title} quá hạn SLA",
                    description: $"Ticket \"{t.Title}\" đã quá hạn xử lý SLA. Vui lòng ưu tiên xử lý.",
                    href: $"/it-tickets/{t.Id}",
                    refId: t.Id,
                    ct: ct);
            }
            t.SlaBreached = true;
        }

        await db.SaveChangesAsync(ct);
        _logger.LogInformation("ItTicketSlaJob: {Count} tickets breached SLA.", breached.Count);
    }

    // Warning: ticket chưa warning + còn open + còn ≤20% window (theo Priority) trước hạn.
    // Notify assignee + set SlaWarnedSent=true. Idempotent qua !SlaWarnedSent guard.
    private async Task ProcessWarningsAsync(
        IApplicationDbContext db, INotificationService notifications,
        DateTime now, CancellationToken ct)
    {
        var candidates = await db.ItTickets
            .Where(t => !t.SlaWarnedSent
                && t.SlaDueAt != null && t.SlaDueAt > now
                && t.Status != ItTicketStatus.Resolved && t.Status != ItTicketStatus.Closed
                && !t.IsDeleted)
            .ToListAsync(ct);

        if (candidates.Count == 0) return;

        int warned = 0;
        foreach (var t in candidates)
        {
            var window = CreateItTicketHandler.SlaWindow.TryGetValue(t.Priority, out var w)
                ? w : TimeSpan.FromHours(24);
            var threshold = TimeSpan.FromTicks((long)(window.Ticks * 0.2));
            var remaining = t.SlaDueAt!.Value - now;
            if (remaining > threshold) continue;       // còn nhiều SLA → skip

            if (t.AssignedToUserId is Guid assignee)
            {
                var hoursLeft = Math.Max(1, (int)remaining.TotalHours);
                await notifications.NotifyAsync(
                    assignee,
                    NotificationType.SlaWarning,
                    title: $"⚠ Ticket {t.MaTicket ?? t.Title} sắp quá hạn ({hoursLeft}h)",
                    description: $"Ticket \"{t.Title}\" còn ~{hoursLeft}h trước hạn xử lý SLA.",
                    href: $"/it-tickets/{t.Id}",
                    refId: t.Id,
                    ct: ct);
            }
            t.SlaWarnedSent = true;
            warned++;
        }

        if (warned > 0)
        {
            await db.SaveChangesAsync(ct);
            _logger.LogInformation("ItTicketSlaJob: {Count} warnings dispatched (≤20% SLA).", warned);
        }
    }
}
