<?php

namespace App\Services;

use App\Models\Product;
use App\Models\ProductVariant;
use App\Models\StockAdjustment;
use App\Models\User;
use Filament\Notifications\Notification;
use Illuminate\Support\Facades\Auth;

class StockAdjustmentService
{
    public static bool $skipObserver = false;

    /**
     * Adjust the stock of a product or variant and log the adjustment.
     */
    public static function adjust($model, int $changeAmount, string $event, array $options = []): void
    {
        if ($changeAmount === 0) {
            return;
        }

        self::$skipObserver = true;

        $oldQty = (int) $model->quantity;
        $newQty = $oldQty + $changeAmount;

        // Update the model quantity
        $model->update(['quantity' => $newQty]);

        // Create adjustment record
        StockAdjustment::create([
            'product_id' => $model instanceof Product ? $model->id : $model->product_id,
            'product_variant_id' => $model instanceof ProductVariant ? $model->id : null,
            'user_id' => $options['user_id'] ?? Auth::id(),
            'order_id' => $options['order_id'] ?? null,
            'return_request_id' => $options['return_request_id'] ?? null,
            'change_amount' => $changeAmount,
            'old_quantity' => $oldQty,
            'new_quantity' => $newQty,
            'event' => $event,
            'notes' => $options['notes'] ?? null,
        ]);

        self::$skipObserver = false;

        // Trigger low stock notifications if threshold crossed
        $securityStock = (int) ($model->security_stock ?? 0);
        if ($newQty <= $securityStock && $oldQty > $securityStock) {
            self::sendLowStockNotification($model, $newQty);
        }
    }

    /**
     * Send database notifications for low stock.
     */
    protected static function sendLowStockNotification($model, int $currentStock): void
    {
        $name = $model instanceof Product ? $model->name : $model->product->name;
        $sku = $model->sku;
        $variantLabel = $model instanceof ProductVariant 
            ? ' (Variant: ' . implode(', ', $model->options ?? []) . ')' 
            : '';

        $body = "Product \"{$name}\"{$variantLabel} [SKU: {$sku}] has fallen below the safety threshold. Only {$currentStock} items remaining.";

        $admins = User::whereIn('role', ['admin', 'staff'])->get();

        if ($admins->count() > 0) {
            $notification = Notification::make()
                ->title('Low Stock Alert')
                ->body($body)
                ->warning()
                ->toDatabase();

            foreach ($admins as $admin) {
                $admin->notifyNow($notification);
            }
        }
    }
}
