<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use App\Models\Tenant;
use Symfony\Component\HttpFoundation\Response;

class TenantMiddleware
{
    public function handle(Request $request, Closure $next): Response
    {
        // Detect tenant from host
        $host = $request->getHost();
        $hostWithoutWww = preg_replace('/^www\./', '', $host);

        // 1. Try Custom Domain First
        $tenant = Tenant::where('custom_domain', $host)
            ->orWhere('custom_domain', $hostWithoutWww)
            ->first();

        if (!$tenant) {
            $parts = explode('.', $host);
            $slug = null;

            // subdomain detection: xxx.shophyfast.com
            if (count($parts) >= 3 && $parts[0] !== 'www') {
                $slug = $parts[0];
            }

            // fallback 1: X-Tenant-Slug header (for local dev / new build)
            if (!$slug) {
                $slug = $request->header('X-Tenant-Slug');
            }

            // fallback 2: ?tenant= query param (old compiled build compatibility)
            if (!$slug) {
                $slug = $request->query('tenant');
            }

            // fallback 3: JSON body { "tenant": "slug" } (POST requests from old build)
            if (!$slug) {
                $slug = $request->input('tenant');
            }

            if (!$slug) {
                return response()->json(['error' => 'Tenant not identified — pass X-Tenant-Slug header or ?tenant= param'], 400);
            }

            $tenant = Tenant::where('business_slug', $slug)->first();

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

            // If accessed via subdomain but has a custom domain, enforce custom domain
            if (!empty($tenant->custom_domain) && !$request->is('api/admin*') && !$request->is('admin*')) {
                return response()->json([
                    'error' => 'This store uses a custom domain.',
                    'redirect_to' => 'http://' . $tenant->custom_domain
                ], 403);
            }
        }

        // Inject tenant into request for downstream use
        $request->merge(['_tenant' => $tenant]);
        app()->instance('tenant', $tenant);

        return $next($request);
    }
}
