<?php

namespace App\Domains\Purchase\Services\Checkout;

use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Catalog\Exceptions\StockReservationExpiredException;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Catalog\Services\CatalogInventoryService;
use App\Domains\Catalog\Services\StockReservationService;
use App\Domains\Purchase\Exceptions\InsufficientStockException;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Services\UserPurchaseLimitService;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

class StartCheckoutService
{
    public function __construct(
        private readonly CatalogInventoryService $inventory,
        private readonly StockReservationService $reservations,
        private readonly UserPurchaseLimitService $purchaseLimits,
        private readonly CatalogSelectionResolver $selections,
        private readonly InsufficientStockMessageBuilder $stockMessages,
        private readonly PurchaseResponseLoader $responses,
        private readonly PurchaseItemSnapshotFactory $snapshots,
    ) {}

    /** @param array<string, mixed> $purchaseData */
    public function start(Tenant $tenant, int $userId, array $purchaseData): Purchase
    {
        return DB::transaction(function () use ($tenant, $userId, $purchaseData): Purchase {
            /** @var Tenant $tenant */
            $tenant = Tenant::query()
                ->lockForUpdate()
                ->findOrFail($tenant->getKey());

            $directItems = $purchaseData['direct_items'] ?? null;
            $cartId = isset($purchaseData['cart_id']) ? (int) $purchaseData['cart_id'] : null;
            unset($purchaseData['direct_items'], $purchaseData['cart_id']);

            if (is_array($directItems)) {
                return $this->startDirectItems(
                    $tenant,
                    $userId,
                    $purchaseData,
                    $directItems,
                );
            }

            if ($cartId === null) {
                throw ValidationException::withMessages([
                    'cart_id' => __('api.purchase.source_required'),
                ]);
            }

            return $this->startFromCart($tenant, $userId, $purchaseData, $cartId);
        });
    }

    /**
     * @param  array<string, mixed>  $purchaseData
     * @param  array<int, array<string, mixed>>  $directItems
     */
    private function startDirectItems(
        Tenant $tenant,
        int $userId,
        array $purchaseData,
        array $directItems,
    ): Purchase {
        $lines = collect(array_values($directItems))
            ->map(function (array $item, int $index): array {
                return [
                    'index' => $index,
                    'catalog_item_id' => (int) $item['catalog_item_id'],
                    'variant_id' => isset($item['variant_id']) ? (int) $item['variant_id'] : null,
                    'quantity' => (int) $item['cantidad'],
                    'field' => "direct_items.{$index}",
                ];
            })
            ->groupBy(fn (array $line): string => sprintf(
                '%d:%s',
                $line['catalog_item_id'],
                $line['variant_id'] === null ? 'none' : (string) $line['variant_id'],
            ))
            ->map(function (Collection $duplicateLines): array {
                $line = $duplicateLines->first();
                $line['quantity'] = (int) $duplicateLines->sum('quantity');

                return $line;
            })
            ->sortBy(fn (array $line): string => sprintf(
                '%020d:%020d',
                $line['catalog_item_id'],
                $line['variant_id'] ?? 0,
            ))
            ->values();

        $resolvedLines = $lines->map(function (array $line) use ($tenant): array {
            $selection = $this->selections->resolve(
                $tenant,
                $line['catalog_item_id'],
                $line['variant_id'],
                $line['field'],
            );

            return [
                ...$line,
                'selection' => $selection,
                'catalog_item' => $selection instanceof Variant
                    ? $selection->catalogItem
                    : $selection,
            ];
        });

        $resolvedLines
            ->groupBy(fn (array $line): int => $line['catalog_item']->getKey())
            ->each(function (Collection $catalogLines) use ($userId): void {
                /** @var CatalogItem $catalogItem */
                $catalogItem = $catalogLines->first()['catalog_item'];
                $availableQuantities = $catalogLines
                    ->map(fn (array $line): ?int => $this->inventory->availableQuantity($line['selection']));
                $maximumAddableCeiling = $availableQuantities->contains(null)
                    ? null
                    : (int) $availableQuantities->sum();
                $this->purchaseLimits->assertCanPurchase(
                    $catalogItem,
                    $userId,
                    (int) $catalogLines->sum('quantity'),
                    maximumAddableCeiling: $maximumAddableCeiling,
                    field: 'direct_items',
                );
            });

        $unavailableItems = $resolvedLines
            ->map(function (array $line): ?array {
                $availableQuantity = $this->inventory->availableQuantity($line['selection']);

                if ($availableQuantity === null || $availableQuantity >= $line['quantity']) {
                    return null;
                }

                return $this->unavailableItem($line, $availableQuantity);
            })
            ->filter()
            ->values()
            ->all();

        if ($unavailableItems !== []) {
            throw new InsufficientStockException($unavailableItems);
        }

        $cart = Cart::query()->create([
            'tenant_codigo' => $tenant->codigo,
            'user_id' => $userId,
            'guest_token' => null,
            'status' => 'checkout',
            'origin' => Cart::ORIGIN_DIRECT_CHECKOUT,
        ]);

        $cartItems = collect();
        foreach ($resolvedLines as $line) {
            $cartItem = $cart->items()->create([
                'catalog_item_id' => $line['catalog_item_id'],
                'variant_id' => $line['variant_id'],
                'cantidad' => $line['quantity'],
            ]);

            $cartItem->setRelation('catalogItem', $line['catalog_item']);
            $cartItem->setRelation('variant', $line['selection'] instanceof Variant ? $line['selection'] : null);
            $cartItems->push($cartItem);
        }

        try {
            $this->reservations->syncCart($cart);
        } catch (\InvalidArgumentException) {
            $unavailable = $resolvedLines
                ->map(function (array $line): ?array {
                    $availableQuantity = $this->inventory->availableQuantity($line['selection']);

                    return $availableQuantity !== null && $availableQuantity < $line['quantity']
                        ? $this->unavailableItem($line, $availableQuantity)
                        : null;
                })
                ->filter()
                ->values()
                ->all();

            throw new InsufficientStockException($unavailable !== [] ? $unavailable : [
                $this->unavailableItem($resolvedLines->first(), 0),
            ]);
        }

        $purchase = $this->createPurchase(
            $tenant,
            $userId,
            $purchaseData,
            (float) $resolvedLines->sum(
                fn (array $line): float => $line['selection']->getPrice() * $line['quantity'],
            ),
            $cart->getKey(),
        );
        $cart->update(['current_purchase_id' => $purchase->getKey()]);
        $this->reservations->attachToPurchase($cart, $purchase, $this->checkoutExpiration());

        $cartItems = $cart->items()->orderBy('id')->lockForUpdate()->get();
        $this->loadCartItems($cartItems);
        $purchase->items()->createMany($this->snapshots->fromCartItems($cartItems));

        return $this->loadPurchase($purchase);
    }

    /**
     * @param  array<string, mixed>  $line
     * @return array{
     *     index: int,
     *     catalog_item_id: int,
     *     variant_id: int|null,
     *     requested_quantity: int,
     *     available_quantity: int,
     *     message: string
     * }
     */
    private function unavailableItem(array $line, int $availableQuantity): array
    {
        return [
            'index' => $line['index'],
            'catalog_item_id' => $line['catalog_item_id'],
            'variant_id' => $line['variant_id'],
            'requested_quantity' => $line['quantity'],
            'available_quantity' => $availableQuantity,
            'message' => $this->stockMessages->build(
                $line['catalog_item'],
                $line['selection'],
                $availableQuantity,
            ),
        ];
    }

    /** @param array<string, mixed> $purchaseData */
    private function startFromCart(
        Tenant $tenant,
        int $userId,
        array $purchaseData,
        int $cartId,
    ): Purchase {
        $cart = $this->resolveCart($tenant, $userId, $cartId);
        $cartItems = $cart->items()->lockForUpdate()->get();

        if ($cartItems->isEmpty()) {
            throw ValidationException::withMessages([
                'cart_id' => __('api.purchase.empty_cart'),
            ]);
        }

        $this->loadCartItems($cartItems);
        $this->verifyTenantItems($tenant, $cartItems);
        $this->assertCartPurchaseLimits($tenant, $userId, $cartItems, $cart->getKey());
        $cart->setRelation('items', $cartItems);
        $this->reservations->syncCart($cart);

        $purchase = $this->createPurchase(
            $tenant,
            $userId,
            $purchaseData,
            $cart->getTotalAmount(),
            $cart->getKey(),
        );
        $cart->update(['current_purchase_id' => $purchase->getKey()]);
        $this->reservations->attachToPurchase($cart, $purchase, $this->checkoutExpiration());
        $purchase->items()->createMany($this->snapshots->fromCartItems($cartItems));

        return $this->loadPurchase($purchase);
    }

    private function resolveCart(Tenant $tenant, int $userId, int $cartId): Cart
    {
        /** @var Cart|null $candidate */
        $candidate = Cart::query()->find($cartId);

        $this->assertCartCanCheckout($candidate, $tenant, $userId);

        $candidatePurchaseId = $candidate->current_purchase_id;
        $currentPurchase = $candidatePurchaseId === null
            ? null
            : Purchase::query()->lockForUpdate()->find($candidatePurchaseId);

        /** @var Cart|null $cart */
        $cart = Cart::query()->lockForUpdate()->find($cartId);

        $this->assertCartCanCheckout($cart, $tenant, $userId);

        if ($cart->current_purchase_id !== $candidatePurchaseId) {
            if ($cart->current_purchase_id !== null) {
                throw ValidationException::withMessages([
                    'cart_id' => __('api.purchase.checkout_in_progress'),
                ]);
            }

            $currentPurchase = null;
        }

        if ($currentPurchase?->status === Purchase::STATUS_PAID) {
            throw ValidationException::withMessages([
                'cart_id' => __('api.purchase.checkout_in_progress'),
            ]);
        }

        if ($currentPurchase !== null && in_array($currentPurchase->status, [
            Purchase::STATUS_CREATED,
            Purchase::STATUS_PENDING_PAYMENT,
        ], true)) {
            $this->reservations->returnToCart($currentPurchase, $cart);
            $currentPurchase->update([
                'status' => Purchase::STATUS_SUPERSEDED,
            ]);
        }

        return $cart;
    }

    private function assertCartCanCheckout(?Cart $cart, Tenant $tenant, int $userId): void
    {
        if ($cart === null || $cart->tenant_codigo !== $tenant->codigo || $cart->user_id !== $userId) {
            throw new NotFoundHttpException('Cart not found for tenant.');
        }

        if ($cart->status === Cart::STATUS_EXPIRED) {
            throw new StockReservationExpiredException;
        }

        if ($cart->status !== Cart::STATUS_ACTIVE) {
            throw ValidationException::withMessages([
                'cart_id' => __('api.purchase.inactive_cart'),
            ]);
        }
    }

    /** @param Collection<int, CartItem> $cartItems */
    private function verifyTenantItems(Tenant $tenant, Collection $cartItems): void
    {
        foreach ($cartItems as $item) {
            if ($item->selectedItem() === null) {
                throw ValidationException::withMessages([
                    'cart_id' => __('api.purchase.catalog_item_missing'),
                ]);
            }

            if ($item->catalogItem?->tenant_code !== $tenant->codigo) {
                throw ValidationException::withMessages([
                    'cart_id' => __('api.purchase.catalog_item_wrong_tenant'),
                ]);
            }
        }
    }

    /** @param Collection<int, CartItem> $cartItems */
    private function assertCartPurchaseLimits(
        Tenant $tenant,
        int $userId,
        Collection $cartItems,
        int $cartId,
    ): void {
        $quantities = $cartItems
            ->groupBy('catalog_item_id')
            ->map(fn (Collection $items): int => (int) $items->sum('cantidad'))
            ->sortKeys();

        $catalogItems = CatalogItem::query()
            ->where('tenant_code', $tenant->codigo)
            ->whereKey($quantities->keys())
            ->orderBy('id')
            ->lockForUpdate()
            ->get()
            ->keyBy('id');

        foreach ($quantities as $catalogItemId => $quantity) {
            /** @var CatalogItem $catalogItem */
            $catalogItem = $catalogItems->get($catalogItemId);
            $this->purchaseLimits->assertCanPurchase(
                $catalogItem,
                $userId,
                $quantity,
                excludedCartId: $cartId,
                heldQuantity: $quantity,
                field: 'cart_id',
            );
        }
    }

    /** @param array<string, mixed> $purchaseData */
    private function createPurchase(
        Tenant $tenant,
        int $userId,
        array $purchaseData,
        float $total,
        ?int $cartId,
    ): Purchase {
        return Purchase::query()->create([
            ...$purchaseData,
            'cart_id' => $cartId,
            'tenant_codigo' => $tenant->codigo,
            'user_id' => $userId,
            'status' => Purchase::STATUS_CREATED,
            'payment_method' => null,
            'total' => $total,
        ]);
    }

    private function checkoutExpiration(): Carbon
    {
        return now()->addMinutes(
            max(1, (int) config('purchase.checkout_expiration_minutes', 30)),
        );
    }

    /** @param Collection<int, CartItem> $cartItems */
    private function loadCartItems(Collection $cartItems): void
    {
        $cartItems->load([
            'catalogItem.inventory',
            'catalogItem.attachments',
            'variant.inventory',
            'variant.attachments',
            'variant.catalogItem',
            'variant.definitions.itemAttribute.attribute',
            'variant.eventDates',
            'variant.eventDate',
        ]);
    }

    private function loadPurchase(Purchase $purchase): Purchase
    {
        return $this->responses->load($purchase);
    }
}
