<?php

namespace App\Master\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Master\Http\Requests\SiteRequest;
use App\Master\Http\Resources\RoleListResource;
use App\Master\Http\Resources\RoleViewResource;
use Illuminate\Http\Request;
use Mtc\MercuryDataModels\Role;

class RoleController extends Controller
{
    public function index(SiteRequest $request): RoleListResource
    {
        $term = $request->input('term');
        $roles = Role::query()
            ->when(
                $request->filled('tenant'),
                fn ($query) => $query->where('tenant', $request->input('tenant'))
            )
            ->when(
                $request->filled('term'),
                fn ($query) => $query->where('name', 'like', "%$term%")
            )
            ->orderBy('name')
            ->with([
                'permissions',
            ])
            ->paginate($request->input('per_page', 15));
        return new RoleListResource($roles);
    }

    public function store(SiteRequest $request): RoleViewResource
    {
        $this->validate($request, [
            'name' => 'required'
        ]);

        $role = Role::create([
            'name' => $request->input('name'),
            'guard_name' => 'web',
            'tenant' => null,
        ]);

        return new RoleViewResource($role);
    }

    public function show(Role $role): RoleViewResource
    {
        return new RoleViewResource($role);
    }

    public function update(Request $request, Role $role): RoleViewResource
    {
        $tenant = $request->input('tenant');
        if ($tenant == 'all') {
            $tenant = null;
        }
        $role->update(['tenant' => $tenant]);
        // todo check if there are users affected by tenant change for role

        $role->permissions()->detach();
        $role->givePermissionTo($request->input('permissions'));
        return new RoleViewResource($role);
    }
}
