<?php

namespace App\Observers;

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

class ProductObserver
{
    public function updated(Product $product): void
    {
        if (StockAdjustmentService::$skipObserver) {
            return;
        }

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

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

                // Check low stock trigger
                $securityStock = (int) ($product->security_stock ?? 0);
                if ($newQty <= $securityStock && $oldQty > $securityStock) {
                    $body = "Product \"{$product->name}\" [SKU: {$product->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);
                        }
                    }
                }
            }
        }
    }
}
