<?php

namespace App\Domains\Link\Services;

use App\Domains\Link\Models\Link;
use Illuminate\Support\Facades\Redis;

class LinkCacheService
{
    private string $prefix = 'link:';

    public function key(string $slug, ?int $domainId = null): string
    {
        return $domainId
            ? "{$this->prefix}{$domainId}:{$slug}"
            : "{$this->prefix}{$slug}";
    }

    /** @param array<string, string> $data */
    public function put(string $slug, array $data, ?int $domainId = null): void
    {
        $key = $this->key($slug, $domainId);
        Redis::hMSet($key, $data);
        Redis::expire($key, 86400);
    }

    /** @return array<string, string>|null */
    public function get(string $slug, ?int $domainId = null): ?array
    {
        $key = $this->key($slug, $domainId);
        $data = Redis::hGetAll($key);

        return empty($data) ? null : $data;
    }

    public function forget(string $slug, ?int $domainId = null): void
    {
        Redis::del($this->key($slug, $domainId));
    }

    public function warmFromLink(Link $link): void
    {
        $this->put($link->slug, [
            'target' => $link->target_url,
            'status' => $link->status,
            'rules_json' => $link->rules ? json_encode($link->rules) : '',
            'expires_at' => $link->expires_at !== null ? (string) $link->expires_at->timestamp : '',
            'workspace_id' => (string) $link->workspace_id,
            'pixel_config' => $link->pixel_config ? json_encode($link->pixel_config) : '',
            'link_id' => (string) $link->id,
        ], $link->domain_id);
    }
}
