using FruitBank.Common.Enums;
using Microsoft.AspNetCore.Mvc;
using Nop.Plugin.Misc.FruitBankPlugin.Domains.DataLayer;
using Nop.Services.Security;
using Nop.Web.Framework.Mvc.Filters;

namespace Nop.Plugin.Misc.FruitBankPlugin.Areas.Admin.Controllers;

public partial class PreorderAdminController
{
    [HttpPost, Route("Admin/Preorders/UpdateHeader/{id:int}")]
    public async Task<IActionResult> UpdateHeader(int id, string deliveryDateTime, string? customerNote)
    {
        if (!await _permissionService.AuthorizeAsync(StandardPermission.Security.ACCESS_ADMIN_PANEL)) return Forbid();
        var p = await _preorderDbContext.Preorders.GetByIdAsync(id);
        if (p == null || p.Status == PreorderStatus.Cancelled) return Json(new { success = false });
        if (!DateTime.TryParse(deliveryDateTime, out var d)) return Json(new { success = false, error = "Érvénytelen dátum" });
        p.DateOfReceipt = d; p.CustomerNote = customerNote?.Trim(); p.UpdatedOnUtc = DateTime.UtcNow;
        await _preorderDbContext.Preorders.UpdateAsync(p);
        return Json(new { success = true });
    }

    [HttpPost, Route("Admin/Preorders/UpdateItem/{id:int}")]
    public async Task<IActionResult> UpdateItem(int id, int quantity, decimal unitPrice)
    {
        if (!await _permissionService.AuthorizeAsync(StandardPermission.Security.ACCESS_ADMIN_PANEL)) return Forbid();
        var item = await _preorderDbContext.PreorderItems.GetByIdAsync(id);
        if (item == null || item.FulfilledQuantity > 0) return Json(new { success = false, error = "Módosítás nem lehetséges" });
        item.RequestedQuantity = Math.Max(1, quantity);
        item.UnitPriceInclTax  = Math.Max(0, unitPrice);
        await _preorderDbContext.PreorderItems.UpdateAsync(item);
        return Json(new { success = true });
    }

    [HttpPost, Route("Admin/Preorders/ReplaceItemProduct/{id:int}")]
    public async Task<IActionResult> ReplaceItemProduct(int id, int newProductId)
    {
        if (!await _permissionService.AuthorizeAsync(StandardPermission.Security.ACCESS_ADMIN_PANEL)) return Forbid();
        var item = await _preorderDbContext.PreorderItems.GetByIdAsync(id);
        if (item == null || item.FulfilledQuantity > 0) return Json(new { success = false, error = "Csere nem lehetséges" });
        var product = await _dbContext.Products.GetByIdAsync(newProductId);
        if (product == null || product.Deleted) return Json(new { success = false, error = "Termék nem található" });

        item.ProductId = newProductId;

        // Recalculate price for the preorder's customer using CustomPriceCalculationService
        var preorder = await _preorderDbContext.Preorders.GetByIdAsync(item.PreorderId);
        var customer = preorder != null ? await _customerService.GetCustomerByIdAsync(preorder.CustomerId) : null;
        if (customer != null)
        {
            var store = await _storeContext.GetCurrentStoreAsync();
            var calc  = await _priceCalculationService.GetFinalPriceAsync(product, customer, store, includeDiscounts: true);
            item.UnitPriceInclTax = calc.finalPrice;
        }

        await _preorderDbContext.PreorderItems.UpdateAsync(item);
        return Json(new { success = true, productName = product.Name, newPrice = item.UnitPriceInclTax });
    }

    [HttpPost, Route("Admin/Preorders/ConvertNow/{id:int}")]
    public async Task<IActionResult> ConvertNow(int id)
    {
        if (!await _permissionService.AuthorizeAsync(StandardPermission.Security.ACCESS_ADMIN_PANEL)) return Forbid();
        var preorder = await _preorderDbContext.Preorders.GetByIdAsync(id);
        if (preorder == null || preorder.Status == PreorderStatus.Cancelled)
            return Json(new { success = false, error = "Konvertálás nem lehetséges" });
        var pending = await _preorderDbContext.PreorderItems.GetAll()
            .Where(i => i.PreorderId == id && i.FulfilledQuantity < i.RequestedQuantity).ToListAsync();
        if (!pending.Any()) return Json(new { success = false, error = "Nincs teljesítetlen tétel" });
        await _preorderConversionService.ConvertPreordersForProductsAsync(
            pending.Select(i => i.ProductId).Distinct().ToList(), 0);
        var refreshed = await _preorderDbContext.Preorders.GetByIdAsync(id);
        return Json(new { success = true, orderId = refreshed?.OrderId });
    }
}
