<?php

declare(strict_types=1);

namespace ServerManager\Models;

use ServerManager\Core\Database;

class ServerPermission
{
    private Database $db;

    public function __construct()
    {
        $this->db = Database::getInstance();
    }

    public function save(int $serverId, array $permissions): void
    {
        $this->deleteByServerId($serverId);

        foreach ($permissions as $perm) {
            if (empty($perm['type']) || !isset($perm['value'])) {
                continue;
            }

            $this->db->insert('server_permissions', [
                'server_id' => $serverId,
                'permission_type' => $perm['type'],
                'permission_value' => $perm['value'],
                'description' => $perm['description'] ?? null,
                'created_at' => date('Y-m-d H:i:s'),
            ]);
        }
    }

    public function getByServerId(int $serverId): array
    {
        return $this->db->fetchAll(
            'SELECT * FROM server_permissions WHERE server_id = ? ORDER BY id ASC',
            [$serverId]
        );
    }

    public function deleteByServerId(int $serverId): void
    {
        $this->db->delete('server_permissions', 'server_id = ?', [$serverId]);
    }

    public static function formatForValidation(array $permissions): array
    {
        return array_map(fn($p) => [
            'type' => $p['permission_type'],
            'value' => $p['permission_value'],
            'description' => $p['description'] ?? '',
        ], $permissions);
    }
}
