using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using WerksverkaufScanner.Data;

namespace WerksverkaufScanner.Services;

public class InventurService
{
    private readonly IDbContextFactory<ScannerDb> _dbFactory;
    private readonly IHttpContextAccessor _http;
    private readonly int _filialId;

    public InventurService(IDbContextFactory<ScannerDb> dbFactory,
                           IHttpContextAccessor http,
                           IConfiguration config)
    {
        _dbFactory = dbFactory;
        _http = http;
        _filialId = config.GetValue<int>("FilialId");
    }

    public async Task<int> SaveAsync(string filialId, int artikelId, int artikelVariantenId, int variante, int menge, string user)
    {
        var clientIp = GetClientIp();
        await using var db = await _dbFactory.CreateDbContextAsync();

        var entry = new InventurErfassung
        {

            FilialId = filialId,
            InventurId = 0,
            ArtikelId = artikelId,
            ArtikelVariantenId = artikelVariantenId,
            Variante = variante,
            Menge = menge,
            ClientIp = clientIp,
            CreatedAt = DateTime.Now,
            Benutzer = user
        };

        db.InventurErfassung.Add(entry);
        return await db.SaveChangesAsync();
    }

    private string? GetClientIp()
    {
        // Falls Reverse-Proxy davorsteht, X-Forwarded-For zuerst prüfen
        var ctx = _http.HttpContext;
        var forwarded = ctx?.Request.Headers["X-Forwarded-For"].FirstOrDefault();
        if (!string.IsNullOrWhiteSpace(forwarded))
            return forwarded.Split(',')[0].Trim();

        return ctx?.Connection.RemoteIpAddress?.ToString();
    }
}
