<?php

namespace App\Http\Controllers;

use App\Http\Resources\SiteUserListResource;
use App\Http\Resources\UserResource;
use App\Master\Models\LiveSiteAccessRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Mtc\MercuryDataModels\Tenant;
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|JsonResponse
     */
    public function setSite(Request $request)
    {
        $selectedSite = $request->input('selected_site');
        $user = $request->user();
        $isMtcUser = $user->hasRole('mtc');

        $tenant = Tenant::find($selectedSite);

        if (!$tenant) {
            return [];
        }

        if (!$isMtcUser && !$user->tenants()->where('tenant_id', $selectedSite)->exists()) {
            return [];
        }

        if ($isMtcUser && $tenant->live_at !== null) {
            $grant = LiveSiteAccessRequest::query()
                ->usable($tenant->id, $user->id, $request->session()->getId())
                ->latest()
                ->first();

            if (!$grant) {
                return response()->json([
                    'message' => 'Live site access approval is required before accessing this site.',
                    'requires_access_request' => true,
                    'tenant_id' => $tenant->id,
                    'tenant_name' => $tenant->name,
                ], 403);
            }

            $grant->consume($request->session()->getId());
        }

        session(['current_tenant' => $selectedSite]);

        return [
            'role' => $user->tenants
                ->filter(fn ($t) => $t->id === $selectedSite)
                ->map(fn ($t) => $t->pivot?->role)
                ->first(),
        ];
    }

    /**
     * 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];
    }
}
