<?php

namespace App\Modules\Settings\Rbac\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Modules\Settings\Rbac\DTOs\RoleWriteData;
use App\Modules\Settings\Rbac\Requests\StoreRoleRequest;
use App\Modules\Settings\Rbac\Requests\UpdateRoleRequest;
use App\Modules\Settings\Rbac\Services\TenantRoleManagementService;
use Illuminate\Http\RedirectResponse;

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

    public function store(StoreRoleRequest $request): RedirectResponse
    {
        $role = $this->roles->create(
            $this->tenant(),
            RoleWriteData::fromValidated($request->validated()),
        );

        return redirect()
            ->route('settings.roles.show', $role)
            ->with('status', __('rbac.flash.role_created'));
    }

    public function update(UpdateRoleRequest $request, int $role): RedirectResponse
    {
        $tenant = $this->tenant();
        $model = $this->roles->find($tenant, $role);
        abort_if($model === null, 404);
        $this->roles->update($tenant, $model, RoleWriteData::fromValidated($request->validated()));

        return redirect()
            ->route('settings.roles.show', $role)
            ->with('status', __('rbac.flash.role_updated'));
    }

    public function destroy(int $role): RedirectResponse
    {
        $tenant = $this->tenant();
        $model = $this->roles->find($tenant, $role);
        abort_if($model === null, 404);
        $this->roles->delete($tenant, $model);

        return redirect()
            ->route('settings.roles.index')
            ->with('status', __('rbac.flash.role_deleted'));
    }

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

        return $tenant;
    }
}
