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

namespace DXApp.TemplateKitProject.Pages.Invoices;

public class ViewAttachmentModel(AttachmentViewerService viewerService) : PageModel
{
    public string FileName { get; private set; } = string.Empty;
    public AttachmentViewerType ViewerType { get; private set; }
    public string? TextContent { get; private set; }

    public IActionResult OnGet(string filePath)
    {
        if (string.IsNullOrEmpty(filePath) || !System.IO.File.Exists(filePath))
            return NotFound();

        FileName = Path.GetFileName(filePath);
        ViewerType = viewerService.DetermineViewerType(FileName);

        // Für Text/XML: Inhalt direkt als Content zurückgeben (für AJAX)
        if (ViewerType == AttachmentViewerType.Xml || ViewerType == AttachmentViewerType.Text)
        {
            TextContent = System.IO.File.ReadAllText(filePath, Encoding.UTF8);
            
            // Wenn Request von AJAX kommt (Accept: */* oder text/plain)
            if (Request.Headers.Accept.ToString().Contains("*/*") || 
                Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                return Content(TextContent, "text/plain", Encoding.UTF8);
            }
        }

        return Page();
    }

    public IActionResult OnGetDownload(string filePath)
    {
        if (string.IsNullOrEmpty(filePath) || !System.IO.File.Exists(filePath))
            return NotFound();

        var fileName = Path.GetFileName(filePath);
        var mimeType = viewerService.GetMimeType(fileName);
        var bytes = System.IO.File.ReadAllBytes(filePath);

        return File(bytes, mimeType, fileName);
    }
}
