<?php

namespace App\Services;

use App\Core\helpers\Generator;
use App\Models\ProtectedUrl;
use App\Repositories\ProtectedUrlRepository;

class ProtectedUrlService {

    use Generator;

    private ProtectedUrlRepository $protectedUrlRepository;

    public function __construct() {
        $this->protectedUrlRepository = new ProtectedUrlRepository();
    }

    public function createProtectedUrl(ProtectedUrl $protectedUrl): string
    {
        $token = bin2hex(random_bytes(32));
        $protectedUrl->token = $token;

        $isExist = $this->protectedUrlRepository->findBy('resource_id', $protectedUrl->resource_id);
        
        if ($isExist) {
            $this->protectedUrlRepository->update($protectedUrl);
        } else {
            $this->protectedUrlRepository->create($protectedUrl);
        }
        
        return rtrim($this->generateRootPath(), '/') . '/project/shared?token=' . urlencode($token);
    }

    public function getProtectedUrl(string $token): ?ProtectedUrl
    {
        return $this->protectedUrlRepository->findBy('token', $token);
    }

    public function getProtectedUrlByProjectId(int $projectId): string
    {
        $protectedUrl = $this->protectedUrlRepository->findBy('resource_id', $projectId);
        // 4️⃣ Construir URL final
        $url = rtrim($this->generateRootPath(), '/') . '/project/shared' . '?token=' . $protectedUrl->token;

        return $url;
    }

}