<?php

namespace App\Modules\Integration\Middleware;

use Closure;
use Illuminate\Http\Request;
use Stancl\Tenancy\Facades\Tenancy;
use Symfony\Component\HttpFoundation\Response;

class TenantIdentificationMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        // 1. Check for X-Tenant-Domain header
        $domain = $request->header('X-Tenant-Domain');

        if (! $domain) {
            return response()->json([
                'message' => 'Missing X-Tenant-Domain header.',
            ], 400);
        }

        // 2. Find Tenant by domain
        // Assuming domains are stored in 'domains' table and linked to tenants
        // Or using Stancl's tenant finder. 
        // Stancl Tenancy usually finds by domain automatically for web routes, but for API 
        // we are doing manual identification because we might not be using subdomains for API calls (or maybe we are).
        // If the API endpoint is centrally hosted (e.g. api.star-erp.com/v1/...), we need this header.
        
        // Let's try to initialize tenancy manually.
        // We need to find the tenant model that has this domain.
        try {
             $tenant = \App\Modules\Core\Models\Tenant::whereHas('domains', function ($query) use ($domain) {
                 $query->where('domain', $domain);
             })->first();

             if (! $tenant) {
                 return response()->json([
                     'message' => 'Tenant not found.',
                 ], 404);
             }

             Tenancy::initialize($tenant);

        } catch (\Exception $e) {
            return response()->json([
                'message' => 'Tenant initialization failed: ' . $e->getMessage(),
            ], 500);
        }

        return $next($request);
    }
}
