using DSaC_second.Models.DTOs;
using DSaC_second.Models.Internal.Queries;
using DSaC_second.Models.Internal.Сommands;
using MediatR;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace DSaC_second.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ContractController : ControllerBase
    {
        private readonly IMediator _mediator;

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

        [HttpGet("")]
        public async Task<IActionResult> GetContracts(
        [FromQuery] int page = 0,
        [FromQuery] int pageSize = 10,
        [FromQuery] List<Guid>? ids = null
        )
        {
            var request = new GetContractsQuery
            {
                Page = page,
                PageSize = pageSize,
                Ids = ids
            };

            var response = await _mediator.Send(request);

            return !response.IsError ? Ok(response.Value) : StatusCode(response.ErrorCode!.Value, response.ErrorText);
        }

        [HttpGet("{uuid:guid}")]
        public async Task<IActionResult> GetFullContract([FromRoute] Guid uuid)
        {
            var request = new GetContractQuery
            {
                Id = uuid
            };

            var response = await _mediator.Send(request);

            return !response.IsError ? Ok(response.Value) : StatusCode(response.ErrorCode!.Value, response.ErrorText);
        }

        [HttpPost("")]
        public async Task<IActionResult> CreateContract([FromBody] ContractBaseDto dto)
        {
            var response = await _mediator.Send(new CreateContractCommand()
            {
                Model = dto
            });

            return !response.IsError ? Ok(response.Value) : StatusCode(response.ErrorCode!.Value, response.ErrorText);
        }

        [HttpPut("{uuid:guid}")]
        public async Task<IActionResult> UpdateContract([FromRoute] Guid uuid, [FromBody] ContractViewDto dto)
        {
            var response = await _mediator.Send(new UpdateContractCommand()
            {
                Id = uuid,
                Model = dto
            });

            return !response.IsError ? Ok(response.Value) : StatusCode(response.ErrorCode!.Value, response.ErrorText);
        }

        [HttpDelete("{uuid:guid}")]
        public async Task<IActionResult> DeleteContract([FromRoute] Guid uuid)
        {
            var response = await _mediator.Send(new DeleteContractCommand()
            {
                Id = uuid,
            });

            return !response.IsError ? Ok() : StatusCode(response.ErrorCode!.Value, response.ErrorText);
        }
    }
}
