using Leanetec.EConnect.Client.Order;
using MediatR;
using Microsoft.AspNetCore.Mvc;

namespace Leanetec.EConnect.Proxy.Controllers;

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

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

    [HttpGet("document")]
    public async Task<IActionResult> GetDocument([FromQuery] GetDocumentRequest request, CancellationToken cancel)
    {
        var res = await _mediator.Send(request, cancel);
        if(res.Ok)
            return res.Data is null || !res.Data.Any()
                ? NotFound()
                : Ok(res.Data);
        else
            return StatusCode(res.StatusCodeInt, res?.Error);
    }

    [HttpPost("document")]
    public async Task<IActionResult> PostDocument(IFormFile file, [FromQuery] PostDocumentRequest request, CancellationToken cancel)
    {
        using var stream = file.OpenReadStream();

        var uploadRequest = request.ToUploadDocument(stream, file.FileName);

        var res = await _mediator.Send(uploadRequest, cancel);

        return res.Ok
            ? StatusCode(res.StatusCodeInt)
            : StatusCode(res.StatusCodeInt, res?.Error);
    }
}