<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Schema;

class RolePermission extends Model
{
    protected $fillable = ['role', 'permission_name', 'allowed'];

    protected function casts(): array
    {
        return ['allowed' => 'boolean'];
    }

    public static function allows(string $role, string $permission): bool
    {
        if ($role === 'super_admin') {
            return true;
        }

        if (! Schema::hasTable('role_permissions')) {
            return static::defaultAllowed($role, $permission);
        }

        $stored = static::where('role', $role)->where('permission_name', $permission)->value('allowed');

        return $stored === null ? static::defaultAllowed($role, $permission) : (bool) $stored;
    }

    public static function defaultAllowed(string $role, string $permission): bool
    {
        if (in_array($role, ['super_admin', 'admin'], true)) {
            return true;
        }

        return in_array($permission, match ($role) {
            'designer' => ['view_dashboard', 'manage_tasks', 'upload_files', 'approve_work'],
            'client' => ['view_dashboard', 'submit_requests', 'download_files', 'upload_files'],
            'gts_client' => ['view_dashboard', 'submit_requests'],
            default => [],
        }, true);
    }
}
