using Asp.Versioning;
using Core.Adapters.Lib;
using Core.Inventory.External.Clients.Inventory;
using Core.Inventory.External.Clients.Inventory.Requests.Variant;
using Microsoft.AspNetCore.Mvc;
using System.Text.Json;
namespace Core.Inventory.BFF.API.Controllers
{
    /// 
    /// Handles all requests for furniture variant operations.
    /// 
    [ApiVersion("1.0")]
    [Route("api/v{version:apiVersion}/[controller]")]
    [ApiController]
    [Consumes("application/json")]
    [Produces("application/json")]
    public class FurnitureVariantController(IInventoryServiceClient inventoryClient, ILogger logger) : BaseController(logger)
    {
        /// 
        /// Gets all furniture base records.
        /// 
        [HttpGet("GetAll")]
        [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)]
        public async Task GetAllVariantsAsync(CancellationToken cancellationToken)
        {
            try
            {
                logger.LogInformation($"{nameof(GetAllVariantsAsync)} - Request received.");
                return await Handle(() => inventoryClient.GetAllVariantsAsync(TrackingId.ToString(), cancellationToken));
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"{nameof(GetAllVariantsAsync)} - An error occurred.");
                throw;
            }
        }
        /// 
        /// Gets furniture variants by model ID.
        /// 
        [HttpPost("GetAllByModelId")]
        [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)]
        public async Task GetAllByModelIdAsync([FromBody] GetAllFurnitureVariantsByModelIdRequest request, CancellationToken cancellationToken)
        {
            try
            {
                logger.LogInformation($"{nameof(GetAllByModelIdAsync)} - Request received. Payload: {JsonSerializer.Serialize(request)}");
                if (string.IsNullOrWhiteSpace(request.ModelId)) return BadRequest("ModelId is required.");
                return await Handle(() => inventoryClient.GetAllVariantsByModelIdAsync(TrackingId.ToString(), request, cancellationToken));
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"{nameof(GetAllByModelIdAsync)} - An error occurred. Payload: {JsonSerializer.Serialize(request)}");
                throw;
            }
        }
        /// 
        /// Gets a furniture variant by its MongoId.
        /// 
        [HttpPost("GetById")]
        [ProducesResponseType(typeof(FurnitureVariant), StatusCodes.Status200OK)]
        public async Task GetByIdAsync([FromBody] GetFurnitureVariantByIdRequest request, CancellationToken cancellationToken)
        {
            try
            {
                logger.LogInformation($"{nameof(GetByIdAsync)} - Request received. Payload: {JsonSerializer.Serialize(request)}");
                if (string.IsNullOrWhiteSpace(request.MongoId)) return BadRequest("MongoId is required.");
                return await Handle(() => inventoryClient.GetFurnitureVariantByIdAsync(TrackingId.ToString(), request, cancellationToken));
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"{nameof(GetByIdAsync)} - An error occurred. Payload: {JsonSerializer.Serialize(request)}");
                throw;
            }
        }
        /// 
        /// Gets furniture variants by a list of IDs.
        /// 
        [HttpPost("GetByIds")]
        [ProducesResponseType(typeof(IEnumerable), StatusCodes.Status200OK)]
        public async Task GetByIdsAsync([FromBody] GetFurnitureVariantsByIdsRequest request, CancellationToken cancellationToken)
        {
            try
            {
                logger.LogInformation($"{nameof(GetByIdsAsync)} - Request received. Payload: {JsonSerializer.Serialize(request)}");
                if (request?.Ids == null || request.Ids.Count == 0)
                    return BadRequest("At least one Id is required.");
                return await Handle(() => inventoryClient.GetFurnitureVariantsByIdsAsync(TrackingId.ToString(), request, cancellationToken));
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"{nameof(GetByIdsAsync)} - An error occurred. Payload: {JsonSerializer.Serialize(request)}");
                throw;
            }
        }
        /// 
        /// Creates a new furniture variant.
        /// 
        [HttpPost("Create")]
        [ProducesResponseType(typeof(FurnitureVariant), StatusCodes.Status201Created)]
        public async Task CreateAsync([FromBody] CreateFurnitureVariantRequest newVariant, CancellationToken cancellationToken)
        {
            try
            {
                logger.LogInformation($"{nameof(CreateAsync)} - Request received. Payload: {JsonSerializer.Serialize(newVariant)}");
                if (newVariant == null) return BadRequest("Invalid furniture object");
                if (string.IsNullOrEmpty(newVariant.ModelId)) return BadRequest("Invalid furniture modelId");
                if (string.IsNullOrEmpty(newVariant.Name)) return BadRequest("Invalid furniture name");
                if (string.IsNullOrEmpty(newVariant.Color)) return BadRequest("Invalid furniture color");
                return await Handle(() => inventoryClient.CreateFurnitureVariantAsync(TrackingId.ToString(), newVariant, cancellationToken));
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"{nameof(CreateAsync)} - An error occurred. Payload: {JsonSerializer.Serialize(newVariant)}");
                throw;
            }
        }
        /// 
        /// Updates a furniture variant.
        /// 
        [HttpPut("Update")]
        [ProducesResponseType(typeof(FurnitureVariant), StatusCodes.Status200OK)]
        public async Task UpdateAsync([FromBody] UpdateFurnitureVariantRequest newVariant, CancellationToken cancellationToken)
        {
            try
            {
                logger.LogInformation($"{nameof(UpdateAsync)} - Request received. Payload: {JsonSerializer.Serialize(newVariant)}");
                if (newVariant == null) return BadRequest("Invalid furniture object");
                if (string.IsNullOrEmpty(newVariant.ModelId)) return BadRequest("Invalid furniture modelId");
                if (string.IsNullOrEmpty(newVariant.Name)) return BadRequest("Invalid furniture name");
                if (string.IsNullOrEmpty(newVariant.Color)) return BadRequest("Invalid furniture color");
                if (string.IsNullOrWhiteSpace(newVariant.Id)) return BadRequest("Id is required.");
                return await Handle(() => inventoryClient.UpdateFurnitureVariantAsync(TrackingId.ToString(), newVariant.Id, newVariant, cancellationToken));
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"{nameof(UpdateAsync)} - An error occurred. Payload: {JsonSerializer.Serialize(newVariant)}");
                throw;
            }
        }
        /// 
        /// Changes the status of a furniture variant.
        /// 
        [HttpPatch("ChangeStatus")]
        [ProducesResponseType(typeof(FurnitureVariant), StatusCodes.Status200OK)]
        public async Task ChangeStatusAsync([FromBody] ChangeFurnitureVariantStatusRequest request, CancellationToken cancellationToken)
        {
            try
            {
                logger.LogInformation($"{nameof(ChangeStatusAsync)} - Request received. Payload: {JsonSerializer.Serialize(request)}");
                if (string.IsNullOrWhiteSpace(request.MongoId)) return BadRequest("Id is required.");
                return await Handle(() => inventoryClient.ChangeFurnitureVariantStatusAsync(TrackingId.ToString(), request, cancellationToken));
            }
            catch (Exception ex)
            {
                logger.LogError(ex, $"{nameof(ChangeStatusAsync)} - An error occurred. Payload: {JsonSerializer.Serialize(request)}");
                throw;
            }
        }
    }
}