using Cortex.Mediator;
using CortexMediatorDemo.API.CQRS.Commands;
using CortexMediatorDemo.API.CQRS.Queries;
using CortexMediatorDemo.API.Domain;
using CortexMediatorDemo.API.Dtos;
using Microsoft.AspNetCore.Mvc;
using Serilog;

namespace CortexMediatorDemo.API.Controllers;

[ApiController]
[Route("[controller]")]
public class BookController(IMediator mediator) : ControllerBase
{
    private readonly IMediator _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));

    [HttpGet("by-id/{id:int}")]
    public async Task<IActionResult> ById(int id)
    {
        try
        {
            var query = new BookByIdQuery(id);
            var result = await _mediator.SendAsync<BookByIdQuery, Book>(query);
            
            // This is using the INotificationHandler
            await _mediator.PublishAsync(query);
            return Ok(result);
        }
        catch (Exception e)
        {
            return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
        }
        
    }

    [HttpPost]
    public async Task<IActionResult> Post([FromBody] BookFroCreationDto bookDto)
    {
        try
        {
            var command = new BookPurchaseCommand(bookDto);
            await _mediator.SendAsync(command);
        }
        catch (Exception e)
        {
            return StatusCode(StatusCodes.Status500InternalServerError, e.Message);
        }
        
        return Ok(bookDto);
    }
    
}