<?php

namespace App\Master\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Master\Models\ImpersonationRequest;
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.');
        }

        $currentUser = Auth::user();

        $impersonationRequest = ImpersonationRequest::query()
            ->where('requester_id', $currentUser->id)
            ->where('target_user_id', $user->id)
            ->usable(session()->getId())
            ->latest()
            ->first();

        if (!$impersonationRequest) {
            return response()->json([
                'message' => 'No approved impersonation request found. Please submit a request first.',
            ], 403);
        }

        $impersonationRequest->update([
            'used_at' => now(),
        ]);

        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,
        ]);
    }
}
