using Asp.Versioning;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Swashbuckle.AspNetCore.Annotations;
using IamService.API.Application.Common;
using IamService.API.Application.Commands.AccessReviews;

namespace IamService.API.Controllers;

[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/access-reviews")]
[Authorize(AuthenticationSchemes = "Bearer")]
[Authorize(Policy = "RequireAdmin")]
[SwaggerTag("Access review management - requires Admin role")]
public class AccessReviewsController : ControllerBase
{
    private readonly IMediator _mediator;
    public AccessReviewsController(IMediator mediator) => _mediator = mediator;

    [HttpPost]
    [SwaggerOperation(Summary = "Create access review", OperationId = "CreateAccessReview")]
    public async Task<IActionResult> Create([FromBody] CreateReviewRequest request, CancellationToken ct = default)
    {
        var id = await _mediator.Send(new CreateAccessReviewCommand(request.Name, request.Description, request.OwnerId, request.Scope, request.DueDate), ct);
        return CreatedAtAction(nameof(GetById), new { id }, ApiResponse<object>.Ok(new { Id = id }));
    }

    [HttpGet("{id:guid}")]
    [SwaggerOperation(Summary = "Get access review by ID", OperationId = "GetAccessReviewById")]
    public async Task<IActionResult> GetById([FromRoute] Guid id, CancellationToken ct = default)
    {
        // Simplified - just return success for now
        return Ok(ApiResponse<object>.Ok(new { Id = id, Message = "Review found" }));
    }

    [HttpPost("{id:guid}/items")]
    [SwaggerOperation(Summary = "Add item to access review", OperationId = "AddAccessReviewItem")]
    public async Task<IActionResult> AddItem([FromRoute] Guid id, [FromBody] AddItemRequest request, CancellationToken ct = default)
    {
        try
        {
            var itemId = await _mediator.Send(new AddAccessReviewItemCommand(id, request.UserId, request.ResourceType, request.ResourceId, request.Permission), ct);
            return Ok(ApiResponse<object>.Ok(new { ItemId = itemId }));
        }
        catch (Exception ex) { return BadRequest(ApiResponse<object>.Fail("ERROR", ex.Message)); }
    }

    [HttpPost("{id:guid}/start")]
    [SwaggerOperation(Summary = "Start access review", OperationId = "StartAccessReview")]
    public async Task<IActionResult> Start([FromRoute] Guid id, CancellationToken ct = default)
    {
        try
        {
            await _mediator.Send(new StartAccessReviewCommand(id), ct);
            return Ok(ApiResponse<object>.Ok(new { Message = "Review started" }));
        }
        catch (Exception ex) { return BadRequest(ApiResponse<object>.Fail("ERROR", ex.Message)); }
    }

    [HttpPost("{id:guid}/items/{itemId:guid}/review")]
    [SwaggerOperation(Summary = "Review an item", OperationId = "ReviewItem")]
    public async Task<IActionResult> ReviewItem([FromRoute] Guid id, [FromRoute] Guid itemId, [FromBody] ReviewItemRequest request, CancellationToken ct = default)
    {
        try
        {
            await _mediator.Send(new ReviewItemCommand(id, itemId, request.ReviewerUserId, request.Certify, request.Comments), ct);
            return Ok(ApiResponse<object>.Ok(new { Message = request.Certify ? "Item certified" : "Item revoked" }));
        }
        catch (Exception ex) { return BadRequest(ApiResponse<object>.Fail("ERROR", ex.Message)); }
    }

    [HttpPost("{id:guid}/complete")]
    [SwaggerOperation(Summary = "Complete access review", OperationId = "CompleteAccessReview")]
    public async Task<IActionResult> Complete([FromRoute] Guid id, CancellationToken ct = default)
    {
        try
        {
            await _mediator.Send(new CompleteAccessReviewCommand(id), ct);
            return Ok(ApiResponse<object>.Ok(new { Message = "Review completed" }));
        }
        catch (Exception ex) { return BadRequest(ApiResponse<object>.Fail("ERROR", ex.Message)); }
    }
}

#region Request Models
public record CreateReviewRequest(string Name, string? Description, Guid OwnerId, string Scope, DateTime DueDate);
public record AddItemRequest(Guid UserId, string ResourceType, Guid ResourceId, string Permission);
public record ReviewItemRequest(Guid ReviewerUserId, bool Certify, string? Comments);
#endregion
