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

namespace PlotLine.Controllers;

[Authorize]
public sealed class ProjectCollaboratorsController(IProjectCollaborationService collaboration) : Controller
{
    public async Task<IActionResult> Index(int projectId)
    {
        var model = await collaboration.GetCollaboratorsAsync(projectId);
        return model is null ? NotFound() : View(model);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Add(ProjectCollaboratorInviteViewModel model)
    {
        if (!ModelState.IsValid)
        {
            TempData["CollaborationError"] = "Enter a valid collaborator email address.";
            return RedirectToAction(nameof(Index), new { projectId = model.ProjectID });
        }

        var result = await collaboration.AddCollaboratorAsync(model);
        if (result.NotFound)
        {
            return NotFound();
        }

        TempData[result.Succeeded ? "CollaborationMessage" : "CollaborationError"] = result.Message;
        return RedirectToAction(nameof(Index), new { projectId = model.ProjectID });
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Remove(int projectId, int userId)
    {
        var result = await collaboration.RemoveCollaboratorAsync(projectId, userId);
        if (result.NotFound)
        {
            return NotFound();
        }

        TempData[result.Succeeded ? "CollaborationMessage" : "CollaborationError"] = result.Message;
        return RedirectToAction(nameof(Index), new { projectId });
    }
}
