<?php
declare(strict_types=1);

namespace App\Modules\Printing;

use PDO;

final class PrintApiKeyRepository
{
    public function __construct(
        private readonly PDO $pdo
    ) {
    }

    public function create(string $name, string $keyHash, string $keyPrefix): int
    {
        $statement = $this->pdo->prepare(
            'INSERT INTO print_api_keys (name, key_hash, key_prefix) VALUES (:name, :key_hash, :key_prefix)'
        );
        $statement->execute([
            'name' => $name,
            'key_hash' => $keyHash,
            'key_prefix' => $keyPrefix,
        ]);

        return (int) $this->pdo->lastInsertId();
    }

    /**
     * @return array<string, mixed>|null
     */
    public function findByKeyHash(string $keyHash): ?array
    {
        $statement = $this->pdo->prepare(
            'SELECT * FROM print_api_keys WHERE key_hash = :key_hash LIMIT 1'
        );
        $statement->execute(['key_hash' => $keyHash]);
        $row = $statement->fetch(PDO::FETCH_ASSOC);

        return is_array($row) ? $row : null;
    }

    /**
     * @return list<array<string, mixed>>
     */
    public function listAll(): array
    {
        $statement = $this->pdo->query(
            'SELECT id, name, key_prefix, is_active, last_used_at, created_at FROM print_api_keys ORDER BY created_at DESC'
        );
        $rows = $statement !== false ? $statement->fetchAll(PDO::FETCH_ASSOC) : [];

        return is_array($rows) ? $rows : [];
    }

    public function deactivate(int $id): void
    {
        $statement = $this->pdo->prepare(
            'UPDATE print_api_keys SET is_active = 0 WHERE id = :id'
        );
        $statement->execute(['id' => $id]);
    }

    public function delete(int $id): void
    {
        $statement = $this->pdo->prepare(
            'DELETE FROM print_api_keys WHERE id = :id'
        );
        $statement->execute(['id' => $id]);
    }

    public function updateLastUsed(int $id): void
    {
        $statement = $this->pdo->prepare(
            'UPDATE print_api_keys SET last_used_at = NOW() WHERE id = :id'
        );
        $statement->execute(['id' => $id]);
    }
}
