using ChapterX.Application.AISuggestion.Commands;
using ChapterX.Application.AISuggestion.Queries;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Linq;

namespace ChapterX.API.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AISuggestionsController : ControllerBase
    {
        private readonly IMediator _mediator;
        private readonly ILogger<AISuggestionsController> _logger;

        public AISuggestionsController(IMediator mediator, ILogger<AISuggestionsController> logger)
        {
            _mediator = mediator;
            _logger = logger;
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<ActionResult> GetAll()
        {
            _logger.LogInformation("Fetching all AI suggestions");
            var response = await _mediator.Send(new GetAllRequest());
            return Ok(response);
        }

        [HttpGet("{id:int}")]
        [AllowAnonymous]
        public async Task<ActionResult> GetById(int id)
        {
            _logger.LogInformation("Fetching AI suggestion with ID: {AISuggestionId}", id);
            var response = await _mediator.Send(new GetRequest(id));
            return Ok(response);
        }

        [HttpGet("chapter/{chapterId:int}")]
        [AllowAnonymous]
        public async Task<ActionResult> GetByChapter(int chapterId)
        {
            _logger.LogInformation("Fetching AI suggestions for ChapterId: {ChapterId}", chapterId);
            var response = await _mediator.Send(new GetByChapterRequest(chapterId));
            var result = response.AISuggestions.Select(s => new
            {
                id = s.Id,
                originalText = s.OriginalText,
                suggestedText = s.SuggestedText,
                accepted = s.Accepted,
                createdAt = s.CreatedAt,
                appliedAt = s.AppliedAt,
                storyId = s.StoryId,
                suggestionTypes = s.SuggestionTypes.Select(t => t.SuggestionTypeValue),
            });
            return Ok(result);
        }

        [HttpPost]
        [Authorize]
        public async Task<ActionResult> Add([FromBody] AddRequest request)
        {
            _logger.LogInformation("Adding a new AI suggestion");
            var response = await _mediator.Send(request);
            return Ok(response);
        }

        [HttpPut("{id:int}")]
        [Authorize]
        public async Task<ActionResult> Update(int id, [FromBody] UpdateRequest request)
        {
            _logger.LogInformation("Updating AI suggestion with ID: {AISuggestionId}", id);
            if (id != request.Id)
            {
                return BadRequest("Route ID and body ID must match.");
            }

            var response = await _mediator.Send(request);
            return Ok(response);
        }

        [HttpDelete("{id:int}")]
        [Authorize]
        public async Task<ActionResult> Delete(int id)
        {
            _logger.LogInformation("Deleting AI suggestion with ID: {AISuggestionId}", id);
            var response = await _mediator.Send(new DeleteRequest(id));
            return Ok(response);
        }
    }
}

