<?php

namespace App\Traits\Restock;

use App\Models\Bottle;
use App\Models\Perfume;
use App\Models\Product;
use App\Models\RestockItem;
use App\Models\Warehouse;

trait WithRestockAddItem
{
    public function addItem(string $type): void
    {
        $this->canOrAbort('create restock');

        if (! $this->form->warehouse_id) {
            $this->toast('Silakan pilih gudang terlebih dahulu.', 'Gagal', 'warning');

            return;
        }

        $warehouse = Warehouse::find($this->form->warehouse_id);

        if (! $warehouse) {
            $this->toast('Gudang tidak ditemukan.', 'Gagal', 'danger');

            return;
        }

        $data = match ($type) {
            'parfum' => [
                'restockable_type' => Perfume::class,
                'restockable_id' => $this->form->perfume_id,
                'quantity' => parseRupiahToInt($this->form->quantity_perfume),
            ],
            'produk' => [
                'restockable_type' => Product::class,
                'restockable_id' => $this->form->product_id,
                'quantity' => parseRupiahToInt($this->form->quantity_product),
            ],
            'botol' => [
                'restockable_type' => Bottle::class,
                'restockable_id' => $this->form->bottle_id,
                'quantity' => parseRupiahToInt($this->form->quantity_bottle),
            ],
            default => null,
        };

        if (! $data || ! $data['restockable_id'] || $data['quantity'] <= 0) {
            $this->toast('Data item tidak valid.', 'Gagal', 'danger');

            return;
        }

        // Validate stock availability
        $relationName = match ($type) {
            'parfum' => 'perfumes',
            'produk' => 'products',
            'botol' => 'bottles',
            default => null,
        };

        if ($relationName) {
            $warehouseStock = $warehouse->{$relationName}()
                ->where($data['restockable_type']::make()->getTable().'.id', $data['restockable_id'])
                ->first()
                ?->pivot
                ?->stock ?? 0;

            // Is item already in cart?
            $existing = RestockItem::where([
                'user_id' => auth()->id(),
                'restockable_id' => $data['restockable_id'],
                'restockable_type' => $data['restockable_type'],
            ])->whereNull('restock_id')->first();

            $currentCartQty = $existing ? $existing->quantity : 0;
            $requestedQty = $data['quantity'];

            if (($currentCartQty + $requestedQty) > $warehouseStock) {
                $this->toast("Stok tidak mencukupi. Stok di gudang: {$warehouseStock}. Sudah di keranjang: {$currentCartQty}.", 'Gagal', 'danger');

                return;
            }

            if ($existing) {
                $existing->increment('quantity', $requestedQty);
            } else {
                RestockItem::create(array_merge($data, ['user_id' => auth()->id()]));
            }
        }

        $this->resetFormItem($type);
        $this->restockItems = $this->loadRestockItems();
        $this->toast('Item berhasil ditambahkan ke keranjang.');
    }

    private function resetFormItem(string $type): void
    {
        if ($type === 'parfum') {
            $this->form->perfume_id = '';
            $this->form->quantity_perfume = '';
        } elseif ($type === 'produk') {
            $this->form->product_id = '';
            $this->form->quantity_product = '';
        } elseif ($type === 'botol') {
            $this->form->bottle_id = '';
            $this->form->quantity_bottle = '';
        }
    }
}
