<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class RolePermission extends Model
{
    use HasFactory;

    protected $fillable = [
        'role',
        'permission_key',
        'is_allowed',
    ];

    protected $casts = [
        'is_allowed' => 'boolean',
    ];

    /**
     * Role constants for client admins.
     */
    const ROLE_CLIENT_OWNER = 'client_owner';
    const ROLE_CLIENT_MANAGER = 'client_manager';

    /**
     * Seed default role permissions.
     */
    public static function seedDefaults(): void
    {
        // SuperAdmin gets all admin-scope permissions
        $superAdminPermissions = Permission::getSuperAdminPermissions();
        foreach ($superAdminPermissions as $permissionKey) {
            self::updateOrCreate(
                ['role' => Admin::ROLE_SUPERADMIN, 'permission_key' => $permissionKey],
                ['is_allowed' => true]
            );
        }

        // Admin gets limited admin-scope permissions
        $allAdminPermissions = Permission::getSuperAdminPermissions();
        $adminPermissions = Permission::getAdminPermissions();

        foreach ($allAdminPermissions as $permissionKey) {
            self::updateOrCreate(
                ['role' => Admin::ROLE_ADMIN, 'permission_key' => $permissionKey],
                ['is_allowed' => in_array($permissionKey, $adminPermissions)]
            );
        }

        // Client Owner gets all client-scope permissions
        $allClientPermissions = collect(Permission::getClientScopePermissions())
            ->pluck('permission_key')
            ->toArray();
        $ownerPermissions = Permission::getClientOwnerPermissions();

        foreach ($allClientPermissions as $permissionKey) {
            self::updateOrCreate(
                ['role' => self::ROLE_CLIENT_OWNER, 'permission_key' => $permissionKey],
                ['is_allowed' => in_array($permissionKey, $ownerPermissions)]
            );
        }

        // Client Manager gets limited client-scope permissions
        $managerPermissions = Permission::getClientManagerPermissions();

        foreach ($allClientPermissions as $permissionKey) {
            self::updateOrCreate(
                ['role' => self::ROLE_CLIENT_MANAGER, 'permission_key' => $permissionKey],
                ['is_allowed' => in_array($permissionKey, $managerPermissions)]
            );
        }
    }
}
