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

namespace PlotLine.Controllers;

[Authorize]
public sealed class PlotThreadsController(IPlotService plots) : Controller
{
    public async Task<IActionResult> Index(int projectId)
    {
        var model = await plots.GetPlotThreadsAsync(projectId);
        return model is null ? NotFound() : View(model);
    }

    public async Task<IActionResult> Create(int projectId, int? plotLineId)
    {
        var model = await plots.GetCreatePlotThreadAsync(projectId, plotLineId);
        return model is null ? NotFound() : View("Edit", model);
    }

    public async Task<IActionResult> Edit(int id)
    {
        var model = await plots.GetEditPlotThreadAsync(id);
        return model is null ? NotFound() : View(model);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Save(PlotThreadEditViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View("Edit", model);
        }

        await plots.SavePlotThreadAsync(model);
        return RedirectToAction(nameof(Index), new { projectId = model.ProjectID });
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Archive(int id, int projectId)
    {
        await plots.ArchivePlotThreadAsync(id);
        TempData["ArchiveMessage"] = "Plot thread archived. You can restore it from Archived Items.";
        return RedirectToAction(nameof(Index), new { projectId });
    }
}
