<?php

namespace App\Http\Controllers\Central;

use App\Http\Controllers\Controller;
use App\Models\Central\Tenant;
use App\Models\User;
use App\Services\AuditLog;
use App\Services\CurrentContext;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;

/**
 * Starts a support impersonation session. The landlord lives on the central
 * domain with the `central` guard, so we can't mint a tenant `web` session cookie
 * here directly. Instead we issue a short-lived single-use token and hand off to
 * the tenant subdomain, where {@see \App\Http\Controllers\ImpersonationController}
 * consumes it and logs in. Every hand-off is written to the tenant's audit trail.
 */
class ImpersonationController extends Controller
{
    public function __construct(private readonly CurrentContext $context) {}

    public function start(Tenant $tenant): Response
    {
        $owner = $this->context->runForTenant($tenant, fn () => User::query()
            ->where('status', User::STATUS_ACTIVE)
            ->whereHas('roles', fn ($q) => $q->where('is_full_admin', true)->where('is_active', true))
            ->first());

        if (! $owner) {
            return back()->with('error', 'This tenant has no active administrator to impersonate.');
        }

        $token = Str::random(48);
        $admin = Auth::guard('central')->user();

        Cache::put("impersonate:{$token}", [
            'user_id' => $owner->id,
            'tenant_id' => $tenant->id,
            'by_email' => $admin?->email,
        ], now()->addMinutes(2));

        $this->context->runForTenant($tenant, fn () => AuditLog::record(
            'tenant.impersonation_started',
            $owner,
            ['central_admin' => $admin?->email],
        ));

        $url = $tenant->url('/impersonate/'.$token);

        // Return the handoff URL as JSON so the client can open it in a new tab.
        return response()->json(['url' => $url]);
    }
}
