using Backend.Common;
using Backend.Models;
using Mediator;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace Backend.API.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ProduitController : ControllerBase
    {
        private const string getAllProduit = "getAll";
        private const string postCreateOrUpdate = "createOrUpdate";
        private const string deleteById = "deleteById/{id}";

        private readonly ILogger<ProduitController> _log;
        private readonly IMediator _mediator;

        public ProduitController(ILogger<ProduitController> log, IMediator mediator)
        {
            _log = log;
            _mediator = mediator;
        }

        /// <summary>
        /// get all type propriete
        /// </summary>
        /// <returns></returns>
        [HttpGet(getAllProduit)]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<IActionResult> GetAll()
        {
            _log.LogDebug($"{this.GetType().Name} -> {MethodBase.GetCurrentMethod()} - Request to get all Type");
            if (_mediator == null)
            {
                _log.LogError($"{this.GetType().Name} -> {MethodBase.GetCurrentMethod()} - {ErrorsConstants.HTTP_ERROR_5XX}");
                return StatusCode(StatusCodes.Status500InternalServerError, ErrorsConstants.HTTP_ERROR_5XX);
            }
            try
            {
                var query = new GetProduitListQuery();
                using Task<IEnumerable<ProduitResponse>> typesTask = _mediator.Send(query);
                await typesTask;
                if (typesTask.IsCompleted && typesTask.IsCompletedSuccessfully)
                {
                    return Ok(typesTask.Result);
                }
                else
                {
                    _log.LogError($"{this.GetType().Name} -> {MethodBase.GetCurrentMethod()} - {ErrorsConstants.HTTP_ERROR_5XX}");
                    return StatusCode(StatusCodes.Status500InternalServerError, ErrorsConstants.HTTP_ERROR_5XX);
                }
            }
            catch (Exception ex)
            {
                _log.LogError($"{this.GetType().Name} -> {MethodBase.GetCurrentMethod()} - Exception:{ex.Message}");
                return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
            }

        }

        /// <summary>
        /// create or update type
        /// </summary>
        /// <param name="cmd"></param>
        /// <returns></returns>
        [HttpPost(postCreateOrUpdate)]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<IActionResult> CreateOrUpdate([FromBody] AddProduitCommand cmd)
        {
            _log.LogDebug($"{this.GetType().Name} -> {MethodBase.GetCurrentMethod()} - Request to create or update Type");
            if (_mediator == null)
            {
                _log.LogError($"{this.GetType().Name} -> {MethodBase.GetCurrentMethod()} - {ErrorsConstants.HTTP_ERROR_5XX}");
                return StatusCode(StatusCodes.Status500InternalServerError, ErrorsConstants.HTTP_ERROR_5XX);
            }
            if(cmd != null)
            {
                try
                {
                    using Task<int> typesTask = _mediator.Send(cmd);
                    await typesTask;
                    if (typesTask.IsCompleted && typesTask.IsCompletedSuccessfully)
                    {
                        return Ok(typesTask.Result);
                    }
                    else
                    {
                        _log.LogError($"{this.GetType().Name} -> {MethodBase.GetCurrentMethod()} - {ErrorsConstants.HTTP_ERROR_5XX}");
                        return StatusCode(StatusCodes.Status500InternalServerError, ErrorsConstants.HTTP_ERROR_5XX);
                    }
                }
                catch (Exception ex)
                {
                    _log.LogError($"{this.GetType().Name} -> {MethodBase.GetCurrentMethod()} - Exception:{ex.Message}");
                    return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
                }
            }
            else
            {
                _log.LogError($"{this.GetType().Name} -> {MethodBase.GetCurrentMethod()} - {ErrorsConstants.HTTP_ERROR_4XX}");
                return StatusCode(StatusCodes.Status400BadRequest, ErrorsConstants.HTTP_ERROR_4XX);
            }
           
        }

        /// <summary>
        /// delete type by id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete(deleteById)]
        [ProducesResponseType(StatusCodes.Status200OK)]
        [ProducesResponseType(StatusCodes.Status400BadRequest)]
        [ProducesResponseType(StatusCodes.Status500InternalServerError)]
        public async Task<IActionResult> DeleteById([FromRoute] Guid id)
        {
            _log.LogDebug($"{this.GetType().Name} -> {MethodBase.GetCurrentMethod()} - Request to delete type by: {id}");
            if (_mediator == null)
            {
                _log.LogError($"{this.GetType().Name} -> {MethodBase.GetCurrentMethod()} - {ErrorsConstants.HTTP_ERROR_5XX}");
                return StatusCode(StatusCodes.Status500InternalServerError, ErrorsConstants.HTTP_ERROR_5XX);
            }
            if (id != null)
            {
                try
                {
                    RemoveProduitCommand removeProduitCommand = new RemoveProduitCommand { Id = id };
                    using Task<int> typesTask = _mediator.Send(removeProduitCommand);
                    await typesTask;
                    if (typesTask.IsCompleted && typesTask.IsCompletedSuccessfully)
                    {
                        return Ok(typesTask.Result);
                    }
                    else
                    {
                        _log.LogError($"{this.GetType().Name} -> {MethodBase.GetCurrentMethod()} - {ErrorsConstants.HTTP_ERROR_5XX}");
                        return StatusCode(StatusCodes.Status500InternalServerError, ErrorsConstants.HTTP_ERROR_5XX);
                    }
                }
                catch (Exception ex)
                {
                    _log.LogError($"{this.GetType().Name} -> {MethodBase.GetCurrentMethod()} - Exception:{ex.Message}");
                    return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
                }
            }
            else
            {
                _log.LogError($"{this.GetType().Name} -> {MethodBase.GetCurrentMethod()} - {ErrorsConstants.HTTP_ERROR_4XX}");
                return StatusCode(StatusCodes.Status400BadRequest, ErrorsConstants.HTTP_ERROR_4XX);
            }

        }
    }
}
