<?php

namespace App\Master\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Mtc\MercuryDataModels\User;
use Illuminate\Http\JsonResponse;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

class ImpersonateController extends Controller
{
    /**
     *  Impersonate User
     *
     * @param User $user
     * @return JsonResponse
     */
    public function impersonate(User $user): JsonResponse
    {
        if ($user->hasRole('mtc') && !Auth::user()->hasPermissionTo('system-owner')) {
            throw new AccessDeniedHttpException('You do not have permission to impersonate this user.');
        }

        session(['impersonate' => $user->id]);
        session()->forget('current_tenant');

        return response()->json([
            'success' => true
        ]);
    }


    /**
     * Stop Impersonate
     *
     * @return JsonResponse
     */
    public function stopImpersonate(): JsonResponse
    {
        session()->forget('impersonate');

        return response()->json([
            'success' => true
        ]);
    }
}
