<?php

namespace App\Domains\Link\Actions;

use App\Domains\Link\Models\Link;
use App\Domains\Link\Services\LinkCacheService;
use App\Domains\Workspace\Models\Workspace;
use App\Models\User;
use Illuminate\Support\Str;

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

    /** @param array<string, mixed> $data */
    public function handle(Workspace $workspace, User $creator, array $data): Link
    {
        $slug = $data['slug'] ?? $this->generateSlug($workspace->id, $data['domain_id'] ?? null);

        $link = Link::create([
            'workspace_id' => $workspace->id,
            'domain_id' => $data['domain_id'] ?? null,
            'slug' => $slug,
            'target_url' => $data['target_url'],
            'title' => $data['title'] ?? null,
            'description' => $data['description'] ?? null,
            'status' => 'active',
            'expires_at' => $data['expires_at'] ?? null,
            'click_limit' => $data['click_limit'] ?? null,
            'rules' => $data['rules'] ?? null,
            'pixel_config' => $data['pixel_config'] ?? null,
            'tags' => $data['tags'] ?? null,
            'created_by' => $creator->id,
            'updated_by' => $creator->id,
        ]);

        $this->cache->warmFromLink($link);

        return $link;
    }

    private function generateSlug(int $workspaceId, ?int $domainId, int $length = 6): string
    {
        do {
            $slug = Str::random($length);
            $exists = Link::where('slug', $slug)
                ->where('workspace_id', $workspaceId)
                ->where('domain_id', $domainId)
                ->exists();
        } while ($exists);

        return $slug;
    }
}
