<?php

namespace App\Http\Controllers\API\v1\Admin\Impersonate;

use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Http\Request;

class LeaveController extends Controller
{
    public function __invoke(Request $request)
    {
        $current = $request->user();
        if (! $current) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }

        $token = null;
        try {
            if (method_exists($current, 'token')) {
                $token = $current->token();
            }
        } catch (\Throwable $e) {
            $token = null;
        }

        $tokenName = $token ? (string) $token->name : '';
        if (strpos($tokenName, 'impersonate:') !== 0) {
            return response()->json([
                'status' => 'failed',
                'message' => 'Anda tidak sedang impersonate.',
            ], 422);
        }

        $impersonatorId = (int) substr($tokenName, strlen('impersonate:'));
        if ($impersonatorId < 1) {
            return response()->json([
                'status' => 'failed',
                'message' => 'Token impersonate tidak sah.',
            ], 422);
        }

        $impersonator = User::find($impersonatorId);
        if (! $impersonator) {
            return response()->json([
                'status' => 'failed',
                'message' => 'Akaun admin asal tidak dijumpai.',
            ], 404);
        }

        // Revoke impersonated token.
        try {
            if ($token) {
                $token->revoke();
            }
        } catch (\Throwable $e) {
            // Best effort.
        }

        $accessToken = $impersonator->createToken('My app', ['admin'])->accessToken;

        activity()
            ->performedOn($impersonator)
            ->withProperties([
                'admin_id' => $impersonator->id,
                'admin_name' => $impersonator->name,
                'admin_email' => $impersonator->email,
                'from_user_id' => $current->id,
                'from_user_email' => $current->email,
                'ip' => $request->ip(),
                'user_agent' => $request->userAgent(),
            ])
            ->log("admin leave impersonation: {$impersonator->email}");

        return response()->json([
            'status' => 'success',
            'message' => 'Berjaya kembali ke akaun asal.',
            'user' => $impersonator,
            'token' => $accessToken,
        ]);
    }
}

