<?php

namespace App\Observers;

use App\Models\ProductVariant;
use App\Models\StockAdjustment;
use App\Services\StockAdjustmentService;
use Illuminate\Support\Facades\Auth;

class ProductVariantObserver
{
    public function updated(ProductVariant $variant): void
    {
        if (StockAdjustmentService::$skipObserver) {
            return;
        }

        if ($variant->wasChanged('quantity')) {
            $oldQty = (int) $variant->getOriginal('quantity');
            $newQty = (int) $variant->quantity;
            $change = $newQty - $oldQty;

            if ($change !== 0) {
                StockAdjustment::create([
                    'product_id' => $variant->product_id,
                    'product_variant_id' => $variant->id,
                    'user_id' => Auth::id(),
                    'change_amount' => $change,
                    'old_quantity' => $oldQty,
                    'new_quantity' => $newQty,
                    'event' => 'manual',
                    'notes' => 'Manual adjustment via variant update.',
                ]);

                // Check low stock trigger
                $securityStock = (int) ($variant->security_stock ?? 0);
                if ($newQty <= $securityStock && $oldQty > $securityStock) {
                    $variantLabel = implode(', ', $variant->options ?? []);
                    $body = "Product \"{$variant->product->name}\" (Variant: {$variantLabel}) [SKU: {$variant->sku}] has fallen below the safety threshold. Only {$newQty} items remaining.";
                    $admins = \App\Models\User::whereIn('role', ['admin', 'staff'])->get();
                    if ($admins->count() > 0) {
                        $notification = \Filament\Notifications\Notification::make()
                            ->title('Low Stock Alert')
                            ->body($body)
                            ->warning()
                            ->toDatabase();
                        foreach ($admins as $admin) {
                            $admin->notifyNow($notification);
                        }
                    }
                }
            }
        }
    }
}
