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

namespace PlotLine.Controllers;

[Authorize]
public sealed class ProjectsController(IProjectService projects) : Controller
{
    public async Task<IActionResult> Index() => View(await projects.ListAsync());

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

    public async Task<IActionResult> Create() => View("Edit", await projects.GetCreateAsync());

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

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Save(ProjectEditViewModel model)
    {
        if (!ModelState.IsValid)
        {
            if (model.ProjectID == 0)
            {
                await projects.PopulateGenrePresetOptionsAsync(model);
            }

            return View("Edit", model);
        }

        var projectId = await projects.SaveAsync(model);
        if (projectId == 0)
        {
            return NotFound();
        }

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

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Archive(int id)
    {
        await projects.ArchiveAsync(id);
        TempData["ArchiveMessage"] = "Project archived. You can restore it from Archived Items.";
        return RedirectToAction(nameof(Index));
    }
}
