<?php

namespace App\Modules\Settings\Rbac\Services;

use App\Models\User;
use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Modules\Navigation\Services\NavigationService;
use App\Modules\Settings\Rbac\Repositories\PermissionRepository;
use App\Modules\Settings\Rbac\Repositories\RoleRepository;
use App\Modules\Settings\Rbac\Repositories\UserRoleRepository;

class TenantRbacBootstrapService
{
    private const OWNER_SLUG = 'owner';

    public function __construct(
        private readonly RoleRepository $roles,
        private readonly PermissionRepository $permissions,
        private readonly UserRoleRepository $userRoles,
    ) {}

    public function ensureOwnerRoleAndAssign(Tenant $tenant, User $user): void
    {
        $role = $this->roles->findBySlug((int) $tenant->id, self::OWNER_SLUG);
        if ($role === null) {
            $role = $this->roles->create([
                'tenant_id' => $tenant->id,
                'name' => 'Owner',
                'slug' => self::OWNER_SLUG,
                'description' => 'Full access within the tenant.',
            ]);
        }
        $ids = $this->permissions->allIdsOrdered();
        $this->permissions->attachToRole((int) $role->id, $ids);
        $this->userRoles->syncRolesForUser($user, (int) $tenant->id, [(int) $role->id]);
        $user->forceFill(['is_tenant_owner' => true])->save();
        TenantPermissionEvaluator::forgetCacheForUser($user);
        NavigationService::forgetForUser($user);
    }
}
