using DXApp.TemplateKitProject.Data;
using DXApp.TemplateKitProject.Models;
using Microsoft.EntityFrameworkCore;

namespace DXApp.TemplateKitProject.Services;

public class ZugferdImportService(
    ZugferdExtractorService extractor,
    ZugferdParserService parser,
    AppDbContext db,
    ILogger<ZugferdImportService> logger)
{
    public async Task<ZugferdInvoice?> ImportAsync(Stream pdfStream, string sourceType, string guidelineId = "")
    {
        var xml = extractor.ExtractXml(pdfStream);

        if (xml is null)
        {
            logger.LogWarning("Kein ZUGFeRD-XML in der PDF-Datei gefunden.");
            return null;
        }

        var invoice = parser.Parse(xml);

        // Duplikatprüfung
        var duplicate = await db.ZugferdInvoices.FirstOrDefaultAsync(i =>
            i.InvoiceNumber == invoice.InvoiceNumber &&
            i.SellerTaxId == invoice.SellerTaxId);

        if (duplicate is not null)
        {
            logger.LogWarning(
                "Duplikat erkannt: Rechnung '{Number}' von '{Seller}' existiert bereits (ID: {Id}).",
                invoice.InvoiceNumber, invoice.SellerName, duplicate.Id);
            return duplicate;
        }

        invoice.SourceType = sourceType;
        invoice.GuidelineId = guidelineId;
        invoice.ImportedAt = DateTime.UtcNow;

        db.ZugferdInvoices.Add(invoice);
        await db.SaveChangesAsync();

        logger.LogInformation(
            "Rechnung '{Number}' von '{Seller}' importiert (ID: {Id}).",
            invoice.InvoiceNumber, invoice.SellerName, invoice.Id);

        return invoice;
    }
}