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

namespace PlotLine.Controllers;

[Authorize]
public sealed class ArchivesController(IArchiveService archives) : Controller
{
    public async Task<IActionResult> Index(int? projectId, string? entityType)
    {
        return View(await archives.GetArchivedItemsAsync(projectId, entityType));
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Archive(string entityType, int entityId, int? projectId, string? archivedReason)
    {
        await archives.ArchiveAsync(entityType, entityId, archivedReason);
        TempData["ArchiveMessage"] = $"{entityType} archived. You can restore it from Archived Items.";
        return RedirectToAction(nameof(Index), new { projectId, entityType });
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Restore(string entityType, int entityId, int? projectId)
    {
        await archives.RestoreAsync(entityType, entityId);
        TempData["ArchiveMessage"] = $"{entityType} restored.";
        return RedirectToAction(nameof(Index), new { projectId, entityType });
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> DeleteForever(string entityType, int entityId, int? projectId, string? confirmationText)
    {
        var result = await archives.DeleteForeverAsync(entityType, entityId, confirmationText ?? string.Empty);
        TempData[result.Succeeded ? "ArchiveMessage" : "ArchiveError"] = result.Message;
        return RedirectToAction(nameof(Index), new { projectId, entityType });
    }
}
