<?php

namespace App\Modules\Admin\Operations\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Admin\Operations\Requests\StoreSupportImpersonationRequest;
use App\Modules\Admin\Operations\Services\SupportImpersonationService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class SupportImpersonationController extends Controller
{
    public function store(StoreSupportImpersonationRequest $request, SupportImpersonationService $svc): RedirectResponse
    {
        $plain = $svc->begin(
            $request->user(),
            (int) $request->validated('target_user_id'),
            (string) $request->validated('reason'),
            $request->ip(),
            $request->userAgent(),
        );
        $request->session()->flash('impersonation_one_time', $plain);

        return redirect()->route('admin.operations.impersonations.consume');
    }

    public function consume(Request $request, SupportImpersonationService $svc): RedirectResponse
    {
        $plain = $request->session()->pull('impersonation_one_time');
        if (! is_string($plain) || $plain === '') {
            abort(403);
        }
        $svc->consume($request->user(), $plain);

        return redirect()->route('dashboard.index');
    }

    public function revoke(Request $request, SupportImpersonationService $svc, string $session): RedirectResponse
    {
        $svc->revoke($request->user(), (int) $session);

        return back()->with('status', __('operations.impersonation_revoked'));
    }
}
