<?php

namespace YourVendor\YourPackage\Multitenancy;

use Spatie\Multitenancy\Models\Tenant;
use Spatie\Multitenancy\TenantFinder\TenantFinder;
use Illuminate\Http\Request;

class ApiTokenTenantFinder extends TenantFinder
{
    public function findForRequest(Request $request): ?Tenant
    {
        // Option 1: Tenant-ID aus Header
        $tenantId = $request->header('X-Tenant-ID');

        // Option 2: Tenant-ID aus API-Token (z.B. Sanctum)
        if (!$tenantId && auth('sanctum')->check()) {
            $token = auth('sanctum')->user()->currentAccessToken();
            $tenantId = $token?->tenant_id;
        }

        // Option 3: Tenant-ID aus authentifiziertem User (wie bei Web)
        if (!$tenantId && auth('sanctum')->check()) {
            $user = auth('sanctum')->user();
            $tenantId = $user->tenant_id;
        }

        if (!$tenantId) {
            return null;
        }

        return Tenant::find($tenantId);
    }
}
