<?php

namespace App\Http\Controllers;

use App\Master\Http\Requests\SiteRequest;
use App\Master\SiteManager;
use App\Http\Requests\AddSiteUserRequest;
use App\Http\Requests\RemoveSiteUserRequest;
use App\Http\Requests\UpdateSiteUserRequest;
use App\Http\Resources\SiteUserListResource;
use Illuminate\Http\Request;
use Mtc\MercuryDataModels\Role;

class SiteUserController extends Controller
{
    public function __construct()
    {
        $this->middleware([
            'permission:manage-site-users',
        ]);
    }

    /**
     * Show list of users assigned to current site
     *
     * @param SiteManager $manager
     * @return SiteUserListResource
     */
    public function show(SiteManager $manager)
    {
        return new SiteUserListResource($manager->getSiteUsers(tenant('id')));
    }

    /**
     * Add user to a site
     *
     * @param AddSiteUserRequest $request
     * @param SiteManager $manager
     * @return SiteUserListResource
     */
    public function store(AddSiteUserRequest $request, SiteManager $manager)
    {
        $manager->addUser($request->input('email'), tenant('id'), $request->input('role'));
        return $this->show($manager);
    }

    /**
     * Update users role on site
     *
     * @param UpdateSiteUserRequest $request
     * @param SiteManager $manager
     * @return SiteUserListResource
     */
    public function update(UpdateSiteUserRequest $request, SiteManager $manager)
    {
        $manager->changeUserRole(tenant('id'), $request->input('userId'), $request->input('role'));
        return $this->show($manager);
    }

    /**
     * Remove user from site
     *
     * @param RemoveSiteUserRequest $request
     * @param SiteManager $manager
     * @return SiteUserListResource
     */
    public function destroy(RemoveSiteUserRequest $request, SiteManager $manager)
    {
        $manager->removeUser($request->input('userId'), tenant('id'));
        return $this->show($manager);
    }

    /**
     * List available user roles on site
     *
     * @param Request $request
     * @return mixed
     */
    public function roles(Request $request)
    {
        return Role::query()
            ->when(
                $request->filled('tenant'),
                fn($query) => $query->where(fn($query) => $query->where('tenant', $request->input('tenant'))
                    ->orWhereNull('tenant'))
            )
            ->notMtc()
            ->get();
    }
}
