using FluentValidation;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Meezi.API.Models.Orders;
using Meezi.API.Services;
using Meezi.Core.Enums;
using Meezi.Core.Interfaces;
using Meezi.Shared;

namespace Meezi.API.Controllers;

[Route("api/cafes/{cafeId}/orders")]
public class OrdersController : CafeApiControllerBase
{
    private readonly IOrderService _orderService;
    private readonly IValidator<CreateOrderRequest> _createValidator;
    private readonly IValidator<UpdateOrderStatusRequest> _statusValidator;
    private readonly IValidator<RecordPaymentsRequest> _paymentsValidator;
    private readonly IValidator<AppendOrderItemsRequest> _appendValidator;
    private readonly IValidator<UpdateOrderSessionRequest> _sessionValidator;

    public OrdersController(
        IOrderService orderService,
        IValidator<CreateOrderRequest> createValidator,
        IValidator<UpdateOrderStatusRequest> statusValidator,
        IValidator<RecordPaymentsRequest> paymentsValidator,
        IValidator<AppendOrderItemsRequest> appendValidator,
        IValidator<UpdateOrderSessionRequest> sessionValidator)
    {
        _orderService = orderService;
        _createValidator = createValidator;
        _statusValidator = statusValidator;
        _paymentsValidator = paymentsValidator;
        _appendValidator = appendValidator;
        _sessionValidator = sessionValidator;
    }

    [HttpGet]
    public async Task<IActionResult> GetOrders(
        string cafeId,
        [FromQuery] OrderStatus? status,
        ITenantContext tenant,
        CancellationToken cancellationToken)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        var data = await _orderService.GetOrdersAsync(cafeId, status, cancellationToken);
        return Ok(new ApiResponse<IReadOnlyList<OrderDto>>(true, data));
    }

    [HttpGet("open")]
    public async Task<IActionResult> GetOpenOrders(
        string cafeId,
        [FromQuery] string? search,
        ITenantContext tenant,
        CancellationToken cancellationToken)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        var data = await _orderService.GetOpenOrdersAsync(cafeId, search, cancellationToken);
        return Ok(new ApiResponse<IReadOnlyList<OrderDto>>(true, data));
    }

    [HttpGet("live")]
    public async Task<IActionResult> GetLiveOrders(string cafeId, ITenantContext tenant, CancellationToken cancellationToken)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        var data = await _orderService.GetLiveOrdersAsync(cafeId, cancellationToken);
        return Ok(new ApiResponse<IReadOnlyList<LiveOrderDto>>(true, data));
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetOrder(string cafeId, string id, ITenantContext tenant, CancellationToken cancellationToken)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        var data = await _orderService.GetOrderAsync(cafeId, id, cancellationToken);
        if (data is null) return NotFoundError();
        return Ok(new ApiResponse<OrderDto>(true, data));
    }

    [HttpPost]
    public async Task<IActionResult> CreateOrder(
        string cafeId,
        [FromBody] CreateOrderRequest request,
        ITenantContext tenant,
        CancellationToken cancellationToken)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        var validation = await _createValidator.ValidateAsync(request, cancellationToken);
        if (!validation.IsValid) return BadRequest(ValidationError(validation));

        var result = await _orderService.CreateOrderAsync(cafeId, tenant, request, cancellationToken);
        if (!result.Success)
            return OrderError(result.ErrorCode!, result.Field);

        return Ok(new ApiResponse<OrderDto>(true, result.Data));
    }

    [HttpPost("{id}/items")]
    public async Task<IActionResult> AppendItems(
        string cafeId,
        string id,
        [FromBody] AppendOrderItemsRequest request,
        ITenantContext tenant,
        CancellationToken cancellationToken)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        var validation = await _appendValidator.ValidateAsync(request, cancellationToken);
        if (!validation.IsValid) return BadRequest(ValidationError(validation));

        var result = await _orderService.AppendOrderItemsAsync(cafeId, id, request, cancellationToken);
        if (!result.Success)
            return OrderError(result.ErrorCode!, result.Field);

        return Ok(new ApiResponse<OrderDto>(true, result.Data));
    }

    [HttpPatch("{id}/items/{itemId}/void")]
    [Authorize(Roles = "Manager,Owner")]
    public async Task<IActionResult> VoidOrderItem(
        string cafeId,
        string id,
        string itemId,
        ITenantContext tenant,
        CancellationToken cancellationToken)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        if (string.IsNullOrEmpty(tenant.UserId))
            return StatusCode(StatusCodes.Status403Forbidden,
                new ApiResponse<object>(false, null, new ApiError("FORBIDDEN", "User context required.")));

        var result = await _orderService.VoidOrderItemAsync(cafeId, id, itemId, tenant.UserId, cancellationToken);
        if (!result.Success)
            return OrderError(result.ErrorCode!, result.Field);

        return Ok(new ApiResponse<OrderDto>(true, result.Data));
    }

    [HttpPost("{id}/transfer")]
    [Authorize(Roles = "Manager,Owner,Waiter")]
    public async Task<IActionResult> TransferTable(
        string cafeId,
        string id,
        [FromBody] TransferTableRequest request,
        ITenantContext tenant,
        CancellationToken cancellationToken)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;

        var result = await _orderService.TransferTableAsync(cafeId, id, request.TargetTableId, cancellationToken);
        if (!result.Success)
            return OrderError(result.ErrorCode!, result.Field);

        return Ok(new ApiResponse<OrderDto>(true, result.Data));
    }

    [HttpPatch("{id}/session")]
    public async Task<IActionResult> UpdateSession(
        string cafeId,
        string id,
        [FromBody] UpdateOrderSessionRequest request,
        ITenantContext tenant,
        CancellationToken cancellationToken)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        var validation = await _sessionValidator.ValidateAsync(request, cancellationToken);
        if (!validation.IsValid) return BadRequest(ValidationError(validation));

        var result = await _orderService.UpdateOrderSessionAsync(cafeId, id, request, cancellationToken);
        if (!result.Success)
            return OrderError(result.ErrorCode!, result.Field);

        return Ok(new ApiResponse<OrderDto>(true, result.Data));
    }

    [HttpPatch("{id}/status")]
    public async Task<IActionResult> UpdateStatus(
        string cafeId,
        string id,
        [FromBody] UpdateOrderStatusRequest request,
        ITenantContext tenant,
        CancellationToken cancellationToken)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        var validation = await _statusValidator.ValidateAsync(request, cancellationToken);
        if (!validation.IsValid) return BadRequest(ValidationError(validation));

        var data = await _orderService.UpdateStatusAsync(cafeId, id, request.Status, cancellationToken);
        if (data is null) return NotFoundError();
        return Ok(new ApiResponse<OrderDto>(true, data));
    }

    [HttpPost("{id}/payments")]
    public async Task<IActionResult> RecordPayments(
        string cafeId,
        string id,
        [FromBody] RecordPaymentsRequest request,
        ITenantContext tenant,
        CancellationToken cancellationToken)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        var validation = await _paymentsValidator.ValidateAsync(request, cancellationToken);
        if (!validation.IsValid) return BadRequest(ValidationError(validation));

        var result = await _orderService.RecordPaymentsAsync(
            cafeId, id, request, tenant.UserId, cancellationToken);
        if (!result.Success) return OrderError(result.ErrorCode!, result.Field);
        return Ok(new ApiResponse<IReadOnlyList<PaymentDto>>(true, result.Data));
    }

    private IActionResult OrderError(string code, string? field = null) =>
        code switch
        {
            "TABLE_NOT_AVAILABLE" => BadRequest(new ApiResponse<object>(
                false, null, new ApiError(code, "Table is not available for new orders.", field))),
            "TABLE_OCCUPIED" => Conflict(new ApiResponse<object>(
                false, null, new ApiError(code, "Table already has an active order.", field))),
            "ORDER_NOT_OPEN" => BadRequest(new ApiResponse<object>(
                false, null, new ApiError(code, "Order is not open for changes.", field))),
            "ORDER_NOT_FOUND" => NotFound(new ApiResponse<object>(
                false, null, new ApiError(code, "Order not found.", field))),
            "ORDER_ALREADY_CLOSED" => BadRequest(new ApiResponse<object>(
                false, null, new ApiError(code, "Order is already closed.", field))),
            "ITEM_NOT_FOUND" => NotFound(new ApiResponse<object>(
                false, null, new ApiError(code, "Line item not found.", field))),
            "ITEM_ALREADY_VOIDED" => BadRequest(new ApiResponse<object>(
                false, null, new ApiError(code, "Line item is already voided.", field))),
            "TABLE_NOT_FOUND" => NotFound(new ApiResponse<object>(
                false, null, new ApiError(code, "Table not found.", field))),
            "TABLE_CLEANING" => BadRequest(new ApiResponse<object>(
                false, null, new ApiError(code, "Table is being cleaned.", field))),
            "NO_OPEN_SHIFT" => BadRequest(new ApiResponse<object>(
                false, null, new ApiError(code, "Open the cash register shift before taking payment.", field))),
            _ => BadRequest(new ApiResponse<object>(
                false, null, new ApiError(code, "Invalid order request.", field)))
        };
}
