<?php

namespace App\Observers;

use App\Models\ReturnRequest;
use App\Models\StockAdjustment;
use App\Services\StockAdjustmentService;

class ReturnRequestObserver
{
    public function created(ReturnRequest $returnRequest): void
    {
        try {
            $order = $returnRequest->order;
            if (!$order) {
                return;
            }
            $typeLabel = $returnRequest->type === 'refund' ? 'Refund' : 'Return';
            $body = "New {$typeLabel} request submitted for Order #{$order->order_number} by {$order->customer_name}. Reason: " . str_replace('_', ' ', $returnRequest->reason);

            $admins = \App\Models\User::whereIn('role', ['admin', 'staff'])->get();
            if ($admins->count() > 0) {
                $dbNotification = \Filament\Notifications\Notification::make()
                    ->title("New {$typeLabel} Request")
                    ->body($body)
                    ->icon('heroicon-o-arrow-path-rounded-square')
                    ->iconColor('warning')
                    ->actions([
                        \Filament\Actions\Action::make('view')
                            ->label('View Request')
                            ->button()
                            ->color('primary')
                            ->markAsRead()
                            ->url(\App\Filament\Resources\ReturnRequestResource::getUrl('edit', ['record' => $returnRequest])),
                    ])
                    ->toDatabase();

                foreach ($admins as $admin) {
                    $admin->notifyNow($dbNotification);
                }
            }
        } catch (\Exception $e) {
            \Illuminate\Support\Facades\Log::error('Failed to send database notification for new return request: ' . $e->getMessage());
        }
    }

    public function updated(ReturnRequest $returnRequest): void
    {
        if (!$returnRequest->wasChanged('status')) {
            return;
        }

        $oldStatus = $returnRequest->getOriginal('status');
        $newStatus = $returnRequest->status;

        // Transition TO processing or completed (when returned goods are actually received back)
        if (in_array($newStatus, ['processing', 'completed']) && !in_array($oldStatus, ['processing', 'completed'])) {
            // Check if already restored
            $alreadyRestored = StockAdjustment::where('return_request_id', $returnRequest->id)
                ->where('event', 'return_received')
                ->exists();

            if (!$alreadyRestored) {
                // Eager load relationships
                $returnRequest->loadMissing('items.orderItem.variant', 'items.orderItem.product');

                foreach ($returnRequest->items as $item) {
                    $orderItem = $item->orderItem;
                    if (!$orderItem) {
                        continue;
                    }

                    if ($orderItem->product_variant_id && $orderItem->variant) {
                        StockAdjustmentService::adjust($orderItem->variant, $item->quantity, 'return_received', [
                            'return_request_id' => $returnRequest->id,
                            'order_id' => $returnRequest->order_id,
                            'notes' => "Restored stock for Variant SKU {$orderItem->product_sku} (Return Request #{$returnRequest->id} status: {$newStatus})",
                        ]);
                    }
                    if ($orderItem->product) {
                        StockAdjustmentService::adjust($orderItem->product, $item->quantity, 'return_received', [
                            'return_request_id' => $returnRequest->id,
                            'order_id' => $returnRequest->order_id,
                            'notes' => "Restored stock for Product SKU {$orderItem->product_sku} (Return Request #{$returnRequest->id} status: {$newStatus})",
                        ]);
                    }
                }
            }
        }
    }
}
