using DbFirst.Application.MassData.Commands;
using DbFirst.Application.MassData.Queries;
using DbFirst.Contracts.MassData;
using MediatR;
using Microsoft.AspNetCore.Mvc;

namespace DbFirst.API.Controllers;

[ApiController]
[Route("api/[controller]")]
public class MassDataController : ControllerBase
{
    private readonly IMediator _mediator;

    public MassDataController(IMediator mediator)
    {
        _mediator = mediator;
    }

    [HttpGet("count")]
    public async Task<ActionResult<int>> GetCount(CancellationToken cancellationToken)
    {
        var count = await _mediator.Send(new GetMassDataCountQuery(), cancellationToken);
        return Ok(count);
    }

    [HttpGet]
    public async Task<ActionResult<IEnumerable<MassDataReadDto>>> GetAll([FromQuery] int? skip, [FromQuery] int? take, CancellationToken cancellationToken)
    {
        int? resolvedTake = take;
        if (resolvedTake is <= 0)
        {
            resolvedTake = null;
        }

        var result = await _mediator.Send(new GetAllMassDataQuery(skip, resolvedTake), cancellationToken);
        return Ok(result);
    }

    [HttpGet("{customerName}")]
    public async Task<ActionResult<MassDataReadDto>> GetByCustomerName(string customerName, CancellationToken cancellationToken)
    {
        var result = await _mediator.Send(new GetMassDataByCustomerNameQuery(customerName), cancellationToken);
        if (result == null)
        {
            return NotFound();
        }

        return Ok(result);
    }

    [HttpPost("upsert")]
    public async Task<ActionResult<MassDataReadDto>> Upsert([FromBody]MassDataWriteDto dto, CancellationToken cancellationToken)
    {
        var result = await _mediator.Send(new UpsertMassDataByCustomerNameCommand(dto), cancellationToken);
        return Ok(result);
    }
}
