<?php

namespace App\Http\Middleware;

use App\Models\Domain;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Schema;
use Symfony\Component\HttpFoundation\Response;

/**
 * Runs first in the 'web' group. Reads the request's Host header, matches it
 * against the domains table, and — if it matches a company's subdomain or a
 * verified custom domain — binds that Company into the container for the
 * rest of the request as currentCompany() (see app/helpers.php).
 *
 * Three outcomes per request:
 *   - Host matches a domain row for an active/read-only company -> bound.
 *   - Host is the platform's own root domain (or a local dev host) -> no
 *     company bound; this is the SaaS control panel context (Phase 2).
 *   - Host matches nothing -> 404. A domain that isn't in our table has no
 *     business resolving to anyone's data, verified or not.
 */
class ResolveTenant
{
    public function handle(Request $request, Closure $next): Response
    {
        // Tables won't exist yet mid-installation (the web installer runs
        // before this migration does) — pass through untouched rather than
        // breaking the install flow.
        if (!Schema::hasTable('domains')) {
            return $next($request);
        }

        $host = $request->getHost();

        if ($this->isRootDomain($host)) {
            return $next($request);
        }

        $domain = Domain::with('company')->where('hostname', $host)->first();

        if (!$domain || !$domain->company) {
            abort(404);
        }

        if ($domain->isCustom() && !$domain->isVerified()) {
            abort(404);
        }

        app()->instance('currentCompany', $domain->company);
        app()->instance('currentDomain', $domain);

        return $next($request);
    }

    private function isRootDomain(string $host): bool
    {
        return in_array($host, array_filter([tenantRootDomain(), 'localhost', '127.0.0.1']), true);
    }
}
