<?php

namespace App\Repositories;

use App\Config\ContextDB;
use App\Models\ProtectedUrl;
use DateTime;
use PDO;

class ProtectedUrlRepository {
    
    private PDO $context;

    public function __construct(){
        $this->context = (new ContextDB())->conn;
    }

    public function create(ProtectedUrl $protectedUrl): string
    {
        $consult = $this->context->prepare("
            INSERT INTO protected_urls (token, resource_id)
                VALUES (:token, :resource_id)
        ");

        $consult->execute([
            'token' => $protectedUrl->token,
            'resource_id' => $protectedUrl->resource_id,
        ]);

        return $protectedUrl->token;
    }

    public function update(ProtectedUrl $protectedUrl)
    {
       $consult = $this->context->prepare("
            UPDATE protected_urls
            SET token = :token
            WHERE resource_id = :resource_id
        ");

        return $consult->execute([
            'token' => $protectedUrl->token,
            'resource_id' => $protectedUrl->resource_id
        ]);
    }

    public function findBy(string $nameColumn, string $value): ?ProtectedUrl
    {
        $consult = $this->context->prepare("SELECT * FROM protected_urls WHERE $nameColumn = :value");
        $consult->execute(['value' => $value]);
        $result = $consult->fetch(PDO::FETCH_ASSOC);

        if (!$result) {
            return null;
        }

        return new ProtectedUrl($result);
    }
}