<?php

declare(strict_types=1);

namespace SeoScope\Repositories;

use PDO;
use SeoScope\Security\Crypto;

final class SettingsRepository
{
    public function __construct(
        private PDO $pdo,
        private string $tablePrefix,
        private int $userId = 1
    ) {}

    public function get(string $name): ?string
    {
        $table = $this->table();
        $stmt = $this->pdo->prepare("SELECT value_text FROM {$table} WHERE user_id = ? AND name = ? LIMIT 1");
        $stmt->execute([$this->userId, $name]);
        $v = $stmt->fetchColumn();
        return is_string($v) ? $v : null;
    }

    public function set(string $name, ?string $value): void
    {
        $table = $this->table();
        $now = date('Y-m-d H:i:s');
        $stmt = $this->pdo->prepare(
            "INSERT INTO {$table} (user_id, name, value_text, updated_at)
             VALUES (?, ?, ?, ?)
             ON DUPLICATE KEY UPDATE value_text = VALUES(value_text), updated_at = VALUES(updated_at)"
        );
        $stmt->execute([$this->userId, $name, $value, $now]);
    }

    public function getSecret(string $name): ?string
    {
        $v = $this->get($name);
        if ($v === null) {
            return null;
        }
        return Crypto::decryptForApp($v);
    }

    public function setSecret(string $name, ?string $plaintext): void
    {
        if ($plaintext === null) {
            $this->set($name, null);
            return;
        }
        $this->set($name, Crypto::encryptForApp($plaintext));
    }

    private function table(): string
    {
        $prefix = $this->tablePrefix;
        if (!preg_match('/^[a-zA-Z0-9_]+$/', $prefix)) {
            $prefix = 'sscope_';
        }
        return '`' . str_replace('`', '``', $prefix . 'settings') . '`';
    }

    /**
     * Resolve user_id for a cron token (public endpoint).
     */
    public static function findUserIdByCronToken(PDO $pdo, string $tablePrefix, string $token): ?int
    {
        $token = trim($token);
        if ($token === '') {
            return null;
        }
        $prefix = $tablePrefix;
        if (!preg_match('/^[a-zA-Z0-9_]+$/', $prefix)) {
            $prefix = 'sscope_';
        }
        $t = '`' . str_replace('`', '``', $prefix . 'settings') . '`';
        $stmt = $pdo->prepare("SELECT user_id FROM {$t} WHERE name = 'cron.token' AND value_text = ? LIMIT 1");
        $stmt->execute([$token]);
        $uid = $stmt->fetchColumn();
        return is_numeric($uid) ? (int) $uid : null;
    }
}

