<?php

namespace App\Modules\Settings\Rbac\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Modules\Settings\Rbac\Models\Role;
use App\Modules\Settings\Rbac\Services\TenantPermissionCatalogService;
use App\Modules\Settings\Rbac\Services\TenantRoleManagementService;
use Illuminate\Http\Request;
use Illuminate\View\View;

class TenantRolesPageController extends Controller
{
    public function __construct(
        private readonly TenantRoleManagementService $roles,
        private readonly TenantPermissionCatalogService $permissionCatalog,
    ) {}

    public function index(Request $request): View
    {
        return view('pages.settings.roles.index', [
            'roles' => $this->roles->paginateForIndex($this->tenant(), $request),
        ]);
    }

    public function create(): View
    {
        return view('pages.settings.roles.create', [
            'matrixGroups' => $this->permissionCatalog->matrixGroups([]),
        ]);
    }

    public function show(int $role): View
    {
        $model = $this->findRole($role);

        return view('pages.settings.roles.show', ['role' => $model]);
    }

    public function edit(int $role): View
    {
        $model = $this->findRole($role);
        $assignedIds = $model->permissions->pluck('id')->all();

        return view('pages.settings.roles.edit', [
            'role' => $model,
            'matrixGroups' => $this->permissionCatalog->matrixGroups($assignedIds),
            'assignedIds' => $assignedIds,
        ]);
    }

    private function findRole(int $role): Role
    {
        $model = $this->roles->find($this->tenant(), $role);
        abort_if($model === null, 404);

        return $model;
    }

    private function tenant(): Tenant
    {
        $tenant = auth()->user()?->tenant;
        abort_if($tenant === null, 403);

        return $tenant;
    }
}
