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

namespace PlotLine.Controllers;

[Authorize]
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);
        }

        int chapterId;
        try
        {
            chapterId = await chapters.SaveAsync(model);
        }
        catch (SubscriptionLimitException ex) when (model.ChapterID == 0)
        {
            ModelState.AddModelError(string.Empty, ex.Message);
            var createModel = await chapters.GetCreateAsync(model.BookID);
            if (createModel is null)
            {
                return NotFound();
            }

            createModel.ChapterNumber = model.ChapterNumber;
            createModel.ChapterTitle = model.ChapterTitle;
            createModel.Summary = model.Summary;
            createModel.RevisionStatusID = model.RevisionStatusID;
            return View("Edit", createModel);
        }

        return RedirectToAction(nameof(Details), new { id = chapterId });
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Archive(int id, int bookId)
    {
        try
        {
            await chapters.ArchiveAsync(id);
        }
        catch (InvalidOperationException ex)
        {
            TempData["ArchiveMessage"] = ex.Message;
            return RedirectToAction(nameof(Details), new { id });
        }

        TempData["ArchiveMessage"] = "Chapter archived. You can restore it from Archived Items.";
        return RedirectToAction("Details", "Books", new { id = bookId });
    }
}
