using FluentValidation;
using Microsoft.AspNetCore.Mvc;
using Meezi.API.Models.Orders;
using Meezi.API.Services;
using Meezi.Core.Authorization;
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 IAuditLogService _audit;
    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;
    private readonly IValidator<CorrectPaymentsRequest> _correctionValidator;

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

    [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));
    }

    /// <summary>Closed orders (delivered/cancelled) of one Iran-calendar day — the
    /// browsing surface for اصلاح سند payment corrections.</summary>
    [HttpGet("closed")]
    public async Task<IActionResult> GetClosedOrders(
        string cafeId,
        ITenantContext tenant,
        CancellationToken cancellationToken,
        [FromQuery] string? date = null,
        [FromQuery] string? branchId = null,
        [FromQuery] int page = 1,
        [FromQuery] int pageSize = 30)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        if (EnsureBranchAccess(branchId, tenant) is { } branchDenied) return branchDenied;

        DateOnly day;
        if (string.IsNullOrWhiteSpace(date)) day = IranCalendar.TodayInIran;
        else if (!DateOnly.TryParse(date, out day))
            return BadRequest(new ApiResponse<object>(
                false, null, new ApiError("VALIDATION_ERROR", "Invalid date (expected YYYY-MM-DD).", "date")));

        if (page < 1) page = 1;
        if (pageSize is < 1 or > 100) pageSize = 30;

        var (items, total) = await _orderService.GetClosedOrdersAsync(
            cafeId, day, branchId, page, pageSize, cancellationToken);
        return Ok(new PagedApiResponse<OrderDto>(true, items, new PagedMeta(total, page, pageSize)));
    }

    [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;
        if (EnsurePermission(tenant, Permission.ProcessOrders) is { } permDenied) return permDenied;
        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;
        if (EnsurePermission(tenant, Permission.EditOrder) is { } permDenied) return permDenied;
        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")]
    public async Task<IActionResult> VoidOrderItem(
        string cafeId,
        string id,
        string itemId,
        ITenantContext tenant,
        CancellationToken cancellationToken)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        if (EnsurePermission(tenant, Permission.VoidOrder) is { } permDenied) return permDenied;
        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);

        await _audit.LogAsync(new AuditEntry
        {
            Category = "Order",
            Action = "ItemVoided",
            EntityType = "Order",
            EntityId = id,
            Summary = $"Voided a line item on order #{result.Data!.DisplayNumber}",
            Details = new { orderId = id, itemId, displayNumber = result.Data.DisplayNumber }
        }, cancellationToken);

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

    [HttpPost("{id}/transfer")]
    public async Task<IActionResult> TransferTable(
        string cafeId,
        string id,
        [FromBody] TransferTableRequest request,
        ITenantContext tenant,
        CancellationToken cancellationToken)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        if (EnsurePermission(tenant, Permission.EditOrder) is { } permDenied) return permDenied;

        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;
        if (EnsurePermission(tenant, Permission.EditOrder) is { } permDenied) return permDenied;
        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;
        if (EnsurePermission(tenant, Permission.UpdateOrderStatus) is { } permDenied) return permDenied;
        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}/cancel")]
    public async Task<IActionResult> CancelOrder(
        string cafeId,
        string id,
        [FromBody] CancelOrderRequest request,
        ITenantContext tenant,
        CancellationToken cancellationToken)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        if (EnsurePermission(tenant, Permission.VoidOrder) is { } forbidden) return forbidden;

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

        await _audit.LogAsync(new AuditEntry
        {
            Category = "Order",
            Action = "OrderCancelled",
            EntityType = "Order",
            EntityId = id,
            Summary = $"Order #{result.Data!.DisplayNumber} cancelled"
                + (string.IsNullOrWhiteSpace(request.Reason) ? "" : $": {request.Reason!.Trim()}"),
            Details = new
            {
                orderId = id,
                displayNumber = result.Data.DisplayNumber,
                total = result.Data.Total,
                reason = request.Reason
            }
        }, cancellationToken);

        return Ok(new ApiResponse<OrderDto>(true, result.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;
        if (EnsurePermission(tenant, Permission.HandlePayments) is { } permDenied) return permDenied;
        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);

        var paidTotal = result.Data!.Sum(p => p.Amount);
        await _audit.LogAsync(new AuditEntry
        {
            Category = "Payment",
            Action = "PaymentRecorded",
            EntityType = "Order",
            EntityId = id,
            Summary = $"Recorded payment(s) totalling {paidTotal:0.##} on order",
            Details = new
            {
                orderId = id,
                total = paidTotal,
                methods = result.Data!.Select(p => new { p.Method, p.Amount })
            }
        }, cancellationToken);

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

    /// <summary>
    /// اصلاح سند — void wrongly-recorded payments and/or record replacements on a
    /// closed order, atomically, with a mandatory reason. Manager/Owner only;
    /// the full before/after is written to the immutable audit trail.
    /// </summary>
    [HttpPost("{id}/payments/corrections")]
    public async Task<IActionResult> CorrectPayments(
        string cafeId,
        string id,
        [FromBody] CorrectPaymentsRequest request,
        ITenantContext tenant,
        CancellationToken cancellationToken)
    {
        if (EnsureCafeAccess(cafeId, tenant) is { } denied) return denied;
        if (EnsurePermission(tenant, Permission.ManageFinancials) is { } forbidden) return forbidden;
        var validation = await _correctionValidator.ValidateAsync(request, cancellationToken);
        if (!validation.IsValid) return BadRequest(ValidationError(validation));

        // Snapshot the payments before the change so the audit row carries a
        // complete before/after picture even after later corrections.
        var before = await _orderService.GetOrderAsync(cafeId, id, cancellationToken);

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

        await _audit.LogAsync(new AuditEntry
        {
            Category = "Payment",
            Action = "PaymentCorrected",
            EntityType = "Order",
            EntityId = id,
            Summary = $"اصلاح سند: voided {request.VoidPaymentIds.Count} payment(s), " +
                      $"recorded {request.Replacements.Count} replacement(s) — {request.Reason}",
            Details = new
            {
                orderId = id,
                displayNumber = result.Data!.DisplayNumber,
                reason = request.Reason,
                voidedPaymentIds = request.VoidPaymentIds,
                paymentsBefore = before?.Payments.Select(p => new { p.Id, p.Method, p.Amount, p.Status }),
                paymentsAfter = result.Data.Payments.Select(p => new { p.Id, p.Method, p.Amount, p.Status }),
                paidAmountAfter = result.Data.PaidAmount,
                orderTotal = result.Data.Total
            }
        }, cancellationToken);

        return Ok(new ApiResponse<OrderDto>(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))),
            "ORDER_ALREADY_CANCELLED" => BadRequest(new ApiResponse<object>(
                false, null, new ApiError(code, "Order is already cancelled.", field))),
            "ORDER_HAS_PAYMENTS" => Conflict(new ApiResponse<object>(
                false, null, new ApiError(code, "Refund the recorded payments before cancelling this order.", 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))),
            "PAYMENT_NOT_FOUND" => NotFound(new ApiResponse<object>(
                false, null, new ApiError(code, "Payment not found on this order.", field))),
            "PAYMENT_ALREADY_REFUNDED" => BadRequest(new ApiResponse<object>(
                false, null, new ApiError(code, "Payment is already refunded.", field))),
            _ => BadRequest(new ApiResponse<object>(
                false, null, new ApiError(code, "Invalid order request.", field)))
        };
}
