using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using PlotLine.Services;
using PlotLine.ViewModels;
using System.Text;

namespace PlotLine.Controllers;

[Authorize]
public sealed class ImportsController(IImportService imports) : Controller
{
    public IActionResult Index() => View(new ImportIndexViewModel
    {
        JsonText = ImportIndexViewModel.SampleJson
    });

    public IActionResult Sample()
        => File(Encoding.UTF8.GetBytes(ImportIndexViewModel.SampleJson), "application/json", "plotline-import-sample.json");

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Preview(ImportIndexViewModel model)
    {
        model = await imports.PreviewAsync(model);
        ModelState.Clear();
        return View("Index", model);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Import(ImportIndexViewModel model)
    {
        var result = await imports.ImportAsync(model);
        if (result.Succeeded && (result.ProjectID.HasValue || result.IsDryRun))
        {
            return View("Result", result);
        }

        model.Preview ??= (await imports.PreviewAsync(model)).Preview;
        model.StatusMessage = result.Message;
        model.TechnicalDetail = result.TechnicalDetail;
        ModelState.Clear();
        return View("Index", model);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> ValidationReport(ImportIndexViewModel model)
    {
        var report = await imports.BuildValidationReportAsync(model);
        return File(Encoding.UTF8.GetBytes(report), "text/plain", "plotline-import-validation-report.txt");
    }
}
