using Meezi.Core.Interfaces;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace Meezi.Infrastructure.ExternalServices;

/// <summary>
/// Taraz (سامانه مودیان) invoice submission. The real API integration is not
/// built yet, so this service NEVER fakes a tracking code outside development —
/// a merchant must not believe invoices reached the tax authority when they
/// did not.
/// </summary>
public class TarazTaxService : ITarazTaxService
{
    private readonly IConfiguration _configuration;
    private readonly IHostEnvironment _environment;
    private readonly ILogger<TarazTaxService> _logger;

    public TarazTaxService(
        IConfiguration configuration,
        IHostEnvironment environment,
        ILogger<TarazTaxService> logger)
    {
        _configuration = configuration;
        _environment = environment;
        _logger = logger;
    }

    public Task<TarazSubmitResult> SubmitDailyInvoicesAsync(
        string cafeId,
        DateTime dateUtc,
        CancellationToken cancellationToken = default)
    {
        if (_environment.IsDevelopment())
        {
            _logger.LogWarning(
                "[DEV TARAZ] Pretend-submitted invoices for cafe {CafeId} date {Date}",
                cafeId,
                dateUtc.Date);
            return Task.FromResult(new TarazSubmitResult(
                true,
                "DEV-TARAZ",
                "Development stub — nothing was sent to the tax authority."));
        }

        var username = _configuration["Taraz:Username"];
        if (string.IsNullOrWhiteSpace(username))
        {
            return Task.FromResult(new TarazSubmitResult(
                false,
                null,
                "سرویس مودیان هنوز پیکربندی نشده است. لطفاً با پشتیبانی تماس بگیرید."));
        }

        // Credentials exist but the actual Taraz API call is not implemented yet.
        // Be honest with the merchant instead of returning a fake tracking code.
        _logger.LogWarning("Taraz submit requested for cafe {CafeId} but the integration is not implemented", cafeId);
        return Task.FromResult(new TarazSubmitResult(
            false,
            null,
            "اتصال مستقیم به سامانه مودیان هنوز در دست توسعه است."));
    }
}
