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

namespace PlotLine.Controllers;

public sealed class ChaptersController(IChapterService chapters) : Controller
{
    public async Task<IActionResult> Details(int id)
    {
        var model = await chapters.GetDetailAsync(id);
        return model is null ? NotFound() : View(model);
    }

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

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

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

        var chapterId = await chapters.SaveAsync(model);
        return RedirectToAction(nameof(Details), new { id = chapterId });
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Archive(int id, int bookId)
    {
        await chapters.ArchiveAsync(id);
        TempData["ArchiveMessage"] = "Chapter archived. You can restore it from Archived Items.";
        return RedirectToAction("Details", "Books", new { id = bookId });
    }
}
