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

namespace PlotLine.Controllers;

[Authorize]
public sealed class BooksController(IBookService books) : Controller
{
    public async Task<IActionResult> Details(int id)
    {
        var model = await books.GetDetailAsync(id);
        return model is null ? NotFound() : View(model);
    }

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

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

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

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

            createModel.BookTitle = model.BookTitle;
            createModel.BookNumber = model.BookNumber;
            createModel.Description = model.Description;
            return View("Edit", createModel);
        }

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

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