using Microsoft.AspNetCore.Mvc;
using Nexus.Api.DTOs;
using Nexus.Api.Services;

namespace Nexus.Api.Controllers;

[ApiController]
[Route("api/v1/projects")]
public class ProjectsController(IProjectService projectService) : ControllerBase
{
    [HttpGet]
    public async Task<IResult> GetAll(CancellationToken ct)
        => Results.Ok(await projectService.GetAllAsync(ct));

    [HttpGet("{id:guid}")]
    public async Task<IResult> GetById(Guid id, CancellationToken ct)
    {
        var project = await projectService.GetByIdAsync(id, ct);
        return project is null ? Results.NotFound() : Results.Ok(project);
    }

    [HttpPost]
    public async Task<IResult> Create([FromBody] CreateProjectRequest request, CancellationToken ct)
    {
        if (string.IsNullOrWhiteSpace(request.Name))
            return Results.ValidationProblem(new Dictionary<string, string[]> { ["name"] = ["Name is required."] });

        var project = await projectService.CreateAsync(request, ct);
        return Results.Created($"/api/v1/projects/{project.Id}", project);
    }

    [HttpPatch("{id:guid}")]
    public async Task<IResult> Update(Guid id, [FromBody] UpdateProjectRequest request, CancellationToken ct)
    {
        var project = await projectService.UpdateAsync(id, request, ct);
        return project is null ? Results.NotFound() : Results.Ok(project);
    }

    [HttpDelete("{id:guid}")]
    public async Task<IResult> Delete(Guid id, CancellationToken ct)
    {
        var result = await projectService.DeleteAsync(id, ct);
        return result.Outcome switch
        {
            ProjectDeleteOutcome.NotFound => Results.NotFound(),
            ProjectDeleteOutcome.Archived => Results.Ok(result.Project),
            _ => Results.NoContent()
        };
    }
}
