<?php

namespace App\Http\Controllers;

use App\Models\Domain;
use Illuminate\Http\Request;
use Illuminate\Http\Response;

/**
 * Answers the reverse proxy's "should I issue a TLS certificate for this
 * hostname?" question (Caddy's on_demand_tls `ask` directive — see
 * deploy/Caddyfile). A 200 means yes; anything else means no.
 *
 * This is the one thing standing between "companies can mask their own
 * domain" and "anyone on the internet can point a domain at us and get a
 * certificate issued in our name" — only a hostname that's sitting in the
 * domains table as a verified custom domain gets a yes.
 *
 * Restricted to loopback callers: the proxy calls this over localhost, and
 * nothing else has a legitimate reason to.
 */
class TenantDomainAskController extends Controller
{
    public function ask(Request $request): Response
    {
        if (!$request->ip() || !in_array($request->ip(), ['127.0.0.1', '::1'], true)) {
            abort(403);
        }

        $hostname = (string) $request->query('domain');

        $isClaimedAndVerified = Domain::query()
            ->where('hostname', $hostname)
            ->where('type', 'custom')
            ->whereNotNull('verified_at')
            ->exists();

        return response('', $isClaimedAndVerified ? 200 : 403);
    }
}
