<?php

namespace App\Repositories;

use App\Config\Database;

class LicenseRepository
{

    /**
     * Revoke all tokens for a license
     * 
     * @throws Exception
     * 
     * @param int $licenseId
     * 
     * @return void
     */
    public function revokeLicenseTokens(int $licenseId): void
    {
        $conn = Database::connection();

        $sql = "
        UPDATE licenses
        SET last_revoked_at = NOW()
        WHERE id = ?
    ";

        $stmt = $conn->prepare($sql);
        $stmt->bind_param('i', $licenseId);
        $stmt->execute();
    }

    /**
     * Get token revoked at for a license
     * 
     * @throws Exception
     * 
     * @return int|null
     * 
     * @param int $licenseId
     */
    public function getTokenRevokedAt(int $licenseId): ?int
    {
        $conn = Database::connection();

        $sql = "
            SELECT UNIX_TIMESTAMP(last_revoked_at) AS revoked_at
            FROM licenses
            WHERE id = ?
            LIMIT 1
        ";

        $stmt = $conn->prepare($sql);
        $stmt->bind_param('i', $licenseId);
        $stmt->execute();

        $row = $stmt->get_result()->fetch_assoc();

        return $row['revoked_at'] ?? null;
    }

}
