<?php

namespace App\Observers;

use App\Models\CompanySetting;
use App\Models\Listing;
use App\Models\ListingPriceHistory;
use App\Models\Setting;
use App\Notifications\ListingPriceDroppedNotification;

class ListingPriceObserver
{
    /**
     * Handle the Listing "created" event.
     */
    public function created(Listing $listing): void
    {
        //
    }

    /**
     * Handle the Listing "updated" event.
     */
    public function updated(Listing $listing): void
    {
        if(!$listing->wasChanged('price')){
            return;
        }


        $lastActive = ListingPriceHistory::query()
            ->where('listing_id', $listing->id)
            ->orderByDesc('created_at')
            ->value('active');

        ListingPriceHistory::create([
            'listing_id' => $listing->id,
            'old_price' => $listing->getOriginal('price'),
            'new_price' => $listing->price,
            'currency' => $listing->currency,
            'active' => $lastActive ?? true

        ]);

        $this->notifySavedUsers($listing);
    }

   
    private function notifySavedUsers(Listing $listing): void
    {
        $new_price = (float) $listing->price;
        $old_price = (float) $listing->getOriginal('price');

        
        if ($new_price >= $old_price || $old_price <= 0) {
            return;
        }

   
        if ($listing->status !== 'published') {
            return;
        }

        if (!Setting::isEnabled(Setting::GLOBAL_NOTIFICATİON_SETTING)) {
            return;
        }

        $company = $listing->consultantProfile?->company;
        if (!$company) {
            return;
        }

        if (!CompanySetting::isEnabledFor($company->id, CompanySetting::NOTIFICATION_SETTING)) {
            return;
        }

      
        $listing->savedByUsers()
            ->chunkById(100, function ($users) use ($listing, $old_price, $new_price) {
                foreach ($users as $user) {
                    $user->notify(
                        new ListingPriceDroppedNotification(
                            $listing,
                            $old_price,
                            $new_price
                        )
                    );
                }
            }, 'users.id', 'id');
    }

    /**
     * Handle the Listing "deleted" event.
     */
    public function deleted(Listing $listing): void
    {
        //
    }

    /**
     * Handle the Listing "restored" event.
     */
    public function restored(Listing $listing): void
    {
        //
    }

    /**
     * Handle the Listing "force deleted" event.
     */
    public function forceDeleted(Listing $listing): void
    {
        //
    }
}
