<?php

namespace App\Domains\Link\Actions;

use App\Domains\Link\Models\Link;
use App\Domains\Link\Services\LinkCacheService;
use App\Models\User;

class UpdateLink
{
    public function __construct(private LinkCacheService $cache) {}

    /** @param array<string, mixed> $data */
    public function handle(Link $link, User $updater, array $data): Link
    {
        $fillable = ['target_url', 'title', 'description', 'status', 'expires_at', 'click_limit', 'rules', 'pixel_config', 'tags'];

        $updates = ['updated_by' => $updater->id];
        foreach ($fillable as $field) {
            if (array_key_exists($field, $data)) {
                $updates[$field] = $data[$field];
            }
        }

        $link->update($updates);

        $this->cache->forget($link->slug, $link->domain_id);
        $fresh = $link->fresh();
        $this->cache->warmFromLink($fresh);

        return $fresh;
    }
}
