using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Nexus.Api.Models;
using Nexus.Api.Services;

namespace Nexus.Api.Controllers;

[Authorize(Roles = "owner")]
[ProducesResponseType(
    typeof(OpenClawAgentConfigurationErrorDto),
    StatusCodes.Status403Forbidden)]
[ProducesResponseType(
    typeof(OpenClawAgentConfigurationErrorDto),
    StatusCodes.Status409Conflict)]
[ProducesResponseType(
    typeof(OpenClawAgentConfigurationErrorDto),
    StatusCodes.Status502BadGateway)]
[ProducesResponseType(
    typeof(OpenClawAgentConfigurationErrorDto),
    StatusCodes.Status503ServiceUnavailable)]
[ProducesResponseType(
    typeof(OpenClawAgentConfigurationErrorDto),
    StatusCodes.Status504GatewayTimeout)]
[ApiController]
[Route("api/v1/docs")]
public class DocsController(IDocService docService) : ControllerBase
{
    [HttpGet]
    [ProducesResponseType(typeof(IReadOnlyList<DocFileInfo>), StatusCodes.Status200OK)]
    public Task<IResult> GetAll(
        [FromQuery] string agentId = "iris",
        CancellationToken cancellationToken = default)
        => OpenClawContentReadEndpoint.ExecuteAsync(async () =>
            Results.Ok(await docService.GetAllAsync(
                agentId,
                cancellationToken)));

    [HttpGet("{**path}")]
    [ProducesResponseType(typeof(DocFileContent), StatusCodes.Status200OK)]
    [ProducesResponseType(typeof(ValidationProblemDetails), StatusCodes.Status400BadRequest)]
    [ProducesResponseType(typeof(ProblemDetails), StatusCodes.Status404NotFound)]
    public Task<IResult> GetFile(
        string path,
        [FromQuery] string agentId = "iris",
        CancellationToken cancellationToken = default)
    {
        if (string.IsNullOrWhiteSpace(path))
        {
            return Task.FromResult<IResult>(
                Results.ValidationProblem(new Dictionary<string, string[]>
            {
                ["path"] = ["Path is required."]
            }));
        }

        return OpenClawContentReadEndpoint.ExecuteAsync(async () =>
        {
            var file = await docService.GetFileAsync(
                path,
                agentId,
                cancellationToken);
            return file is null ? Results.NotFound() : Results.Ok(file);
        });
    }
}
