<?php

namespace App\Observers;

use App\Helpers\FirstParty\ImageHash\ImageHashService;
use App\Models\MemeMedia;

class MemeMediaObserver
{
    private ImageHashService $imageHashService;

    public function __construct(ImageHashService $imageHashService)
    {
        $this->imageHashService = $imageHashService;
    }

    /**
     * Handle the MemeMedia "created" event.
     */
    public function created(MemeMedia $memeMedia): void
    {
        $this->generateHashIfNeeded($memeMedia);
    }

    /**
     * Handle the MemeMedia "updated" event.
     */
    public function updated(MemeMedia $memeMedia): void
    {
        if ($memeMedia->wasChanged('webp_url')) {
            $this->generateHashIfNeeded($memeMedia);
        }
    }

    private function generateHashIfNeeded(MemeMedia $memeMedia): void
    {
        if ($memeMedia->webp_url && ! $memeMedia->image_hash) {
            $hash = $this->imageHashService->generateHashFromUrl($memeMedia->webp_url);
            if ($hash) {
                $memeMedia->updateQuietly(['image_hash' => $hash]);
            }
        }
    }

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

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

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