<?php

namespace App\Http\Controllers;

use App\Http\Resources\SiteUserListResource;
use App\Http\Resources\UserResource;
use Illuminate\Http\Request;
use Mtc\MercuryDataModels\User;

class UserController extends Controller
{
    /**
     * Show details of current active user on system.
     * User determined on current session.
     *
     * @param Request $request
     * @return mixed
     */
    public function show(Request $request)
    {
        return new UserResource($request->user());
    }

    /**
     * List users added to the current active site.
     * Site determined on current session.
     *
     * @return SiteUserListResource
     */
    public function siteUsers()
    {
        $users = User::query()
            ->latest()
            ->whereHas('tenants', function ($site_query) {
                $site_query->where('tenant_id', tenant('id'));
            })->paginate();

        return new SiteUserListResource($users);
    }

    /**
     * Set currently accessed site
     * @param Request $request
     * @return array
     */
    public function setSite(Request $request)
    {
        if ($request->user()->tenants()->where('tenant_id', $request->input('selected_site'))->exists()) {
            session('current_tenant', $request->input('selected_site'));
            return [
                'role' => $request->user()->tenants
                    ->filter(fn ($tenant) => $tenant->id === $request->input('selected_site'))
                    ->map(fn ($tenant) => $tenant->pivot?->role)
                    ->first()
            ];
        }
        return [];
    }

    /**
     * Toggle a site as favourite for the current user
     * @param Request $request
     * @return array
     */
    public function toggleFavouriteSite(Request $request)
    {
        $request->validate([
            'site_id' => 'required|string',
        ]);

        $user = $request->user();
        $siteId = $request->input('site_id');

        if ($user->favouriteSites()->where('tenant_id', $siteId)->exists()) {
            $user->favouriteSites()->detach($siteId);
            return ['is_favourite' => false];
        }

        $user->favouriteSites()->attach($siteId);
        return ['is_favourite' => true];
    }
}
