using DXApp.TemplateKitProject.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;

namespace DXApp.TemplateKitProject.Pages;

public class TestSignatureModel(
    PdfSigningService signingService,
    IConfiguration configuration,
    ILogger<TestSignatureModel> logger) : PageModel
{
    [BindProperty]
    public IFormFile? PdfFile { get; set; }

    public bool Success { get; private set; }
    public string? ErrorMessage { get; private set; }
    public string? OriginalFileName { get; private set; }
    public long OriginalSizeKb { get; private set; }
    public string? SignedFileName { get; private set; }
    public long SignedSizeKb { get; private set; }
    public string? OutputPath { get; private set; }
    public List<SignatureInformation>? SignatureInfo { get; private set; }

    public void OnGet()
    {
    }

    public async Task<IActionResult> OnPostAsync()
    {
        if (PdfFile is null || PdfFile.Length == 0)
        {
            ModelState.AddModelError(nameof(PdfFile), "Bitte eine PDF-Datei auswählen.");
            return Page();
        }

        if (!PdfFile.FileName.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase))
        {
            ModelState.AddModelError(nameof(PdfFile), "Nur PDF-Dateien sind erlaubt.");
            return Page();
        }

        try
        {
            OriginalFileName = PdfFile.FileName;

            // PDF in Byte-Array laden
            using var memStream = new MemoryStream();
            await PdfFile.CopyToAsync(memStream);
            var originalBytes = memStream.ToArray();
            OriginalSizeKb = originalBytes.Length / 1024;

            logger.LogInformation("Signiere PDF: {FileName} ({Size} KB)", OriginalFileName, OriginalSizeKb);

            // PDF signieren
            var signedBytes = await signingService.SignPdfAsync(originalBytes);
            SignedSizeKb = signedBytes.Length / 1024;

            // Speichern
            var outputDir = configuration["PdfResults:OutputDirectory"] ?? Path.GetTempPath();
            Directory.CreateDirectory(outputDir);

            SignedFileName = Path.GetFileNameWithoutExtension(PdfFile.FileName) + "_signed.pdf";
            OutputPath = Path.Combine(outputDir, SignedFileName);

            await System.IO.File.WriteAllBytesAsync(OutputPath, signedBytes);

            logger.LogInformation("Signierte PDF gespeichert: {Path}", OutputPath);

            // Signatur-Informationen auslesen
            SignatureInfo = await signingService.GetSignatureInfoAsync(signedBytes);

            Success = true;
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "Fehler beim Signieren der PDF: {FileName}", PdfFile.FileName);
            ErrorMessage = ex.Message;
        }

        return Page();
    }
}
