<?php

declare(strict_types=1);

namespace App\Modules\Administration\Repositories;

use PDO;
use System\Contracts\DatabaseInterface;

final class AuthorizationRepository
{
    private PDO $pdo;

    public function __construct(
        DatabaseInterface $database
    ) {
        $this->pdo = $database->getConnection();
    }

    public function userPermissions(
        int $userId
    ): array {
        $statement = $this->pdo->prepare(
            'SELECT DISTINCT
                p.permission_name
             FROM permissions p
             INNER JOIN role_permissions rp
                ON rp.permission_id = p.id
             INNER JOIN user_roles ur
                ON ur.role_id = rp.role_id
             INNER JOIN roles r
                ON r.id = ur.role_id
             WHERE ur.user_id = ?
               AND p.active = 1
               AND r.active = 1'
        );

        $statement->execute([
            $userId
        ]);

        return $statement->fetchAll(
            PDO::FETCH_COLUMN
        );
    }

    public function userRoles(
        int $userId
    ): array {
        $statement = $this->pdo->prepare(
            'SELECT r.role_name
             FROM roles r
             INNER JOIN user_roles ur
                ON ur.role_id = r.id
             WHERE ur.user_id = ?
               AND r.active = 1'
        );

        $statement->execute([
            $userId
        ]);

        return $statement->fetchAll(
            PDO::FETCH_COLUMN
        );
    }
}