using Meezi.API.Services;
using Meezi.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;

namespace Meezi.API.Jobs;

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

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

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

        var reportDate = IranCalendar.TodayInIran.AddDays(-1);

        var branches = await db.Branches
            .Where(b => b.IsActive && b.DeletedAt == null)
            .Select(b => new { b.Id, b.CafeId })
            .ToListAsync();

        var success = 0;
        var failed = 0;

        foreach (var branch in branches)
        {
            try
            {
                await reports.GenerateReportAsync(branch.CafeId, branch.Id, reportDate);
                success++;
            }
            catch (Exception ex)
            {
                failed++;
                _logger.LogWarning(
                    ex,
                    "Failed daily report for cafe {CafeId} branch {BranchId} date {Date}",
                    branch.CafeId,
                    branch.Id,
                    reportDate);
            }
        }

        _logger.LogInformation(
            "Yesterday daily reports ({Date}): {Success} ok, {Failed} failed",
            reportDate,
            success,
            failed);
    }
}
