<?php

namespace FluxCms\Core\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class DomainDetection
{
    /**
     * Handle an incoming request.
     */
    public function handle(Request $request, Closure $next): Response
    {
        if (! config('flux-cms.domains.enabled')) {
            return $next($request);
        }

        $domainKey = $this->detectDomainKey($request);

        // Set domain key in request for later use
        $request->attributes->set('flux_cms_domain_key', $domainKey);

        // Set locale based on domain if configured
        $this->setLocaleFromDomain($request, $domainKey);

        return $next($request);
    }

    /**
     * Detect domain key from request
     */
    protected function detectDomainKey(Request $request): string
    {
        $host = $request->getHost();
        $domains = config('domains.domains', []);

        foreach ($domains as $key => $config) {
            if (isset($config['url'])) {
                $domainHost = parse_url($config['url'], PHP_URL_HOST);
                if ($domainHost === $host) {
                    return $key;
                }
            }
        }

        return config('flux-cms.domains.default_domain', 'default');
    }

    /**
     * Set locale based on domain configuration
     */
    protected function setLocaleFromDomain(Request $request, string $domainKey): void
    {
        $domains = config('domains.domains', []);

        if (isset($domains[$domainKey]['locale'])) {
            $locale = $domains[$domainKey]['locale'];
            app()->setLocale($locale);
        }
    }
}
