using Meezi.Core.Enums;
using Meezi.Core.Interfaces;
using Meezi.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;

namespace Meezi.API.Jobs;

public class SubscriptionRenewalReminderJob
{
    private readonly IServiceScopeFactory _scopeFactory;
    private readonly ILogger<SubscriptionRenewalReminderJob> _logger;

    public SubscriptionRenewalReminderJob(
        IServiceScopeFactory scopeFactory,
        ILogger<SubscriptionRenewalReminderJob> logger)
    {
        _scopeFactory = scopeFactory;
        _logger = logger;
    }

    public async Task ExecuteAsync()
    {
        await using var scope = _scopeFactory.CreateAsyncScope();
        var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
        var sms = scope.ServiceProvider.GetRequiredService<ISmsService>();

        var windowStart = DateTime.UtcNow.Date;
        var windowEnd = windowStart.AddDays(3);

        var cafes = await db.Cafes
            .Where(c => c.PlanTier != PlanTier.Free
                && c.PlanExpiresAt != null
                && c.PlanExpiresAt >= windowStart
                && c.PlanExpiresAt <= windowEnd)
            .ToListAsync();

        foreach (var cafe in cafes)
        {
            var ownerPhone = await db.Employees
                .Where(e => e.CafeId == cafe.Id && e.Role == EmployeeRole.Owner)
                .Select(e => e.Phone)
                .FirstOrDefaultAsync();

            if (string.IsNullOrEmpty(ownerPhone)) continue;

            var message =
                $"میزی: اشتراک {cafe.PlanTier} شما تا {cafe.PlanExpiresAt:yyyy-MM-dd} منقضی می‌شود. از تنظیمات داشبورد تمدید کنید.";
            try
            {
                await sms.SendMessageAsync(ownerPhone, message);
            }
            catch (Exception ex)
            {
                _logger.LogWarning(ex, "Renewal SMS failed for cafe {CafeId}", cafe.Id);
            }
        }

        _logger.LogInformation("Subscription renewal reminders sent for {Count} cafes", cafes.Count);
    }
}
