<?php

namespace App\Http\Controllers;

use App\Domains\Bio\Models\BioPage;
use App\Domains\Domain\Models\Domain;
use App\Domains\Workspace\Models\Workspace;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Symfony\Component\HttpFoundation\Response;

class BioPageController extends Controller
{
    /**
     * Free-plan: nimu.li/b/{workspaceSlug}/{slug}
     * Pro+ workspaces: 301 redirect to their subdomain URL.
     */
    public function showFree(string $workspaceSlug, string $slug): View|Response
    {
        $ws = Workspace::where('slug', $workspaceSlug)->firstOrFail();

        if ($ws->isPaidPlan() && $ws->subdomain_full) {
            return redirect("https://{$ws->subdomain_full}/b/{$slug}", 301);
        }

        $bio = BioPage::where('workspace_id', $ws->id)
            ->where('slug', $slug)
            ->whereNull('subdomain_host')
            ->where('is_published', true)
            ->with('blocks')
            ->firstOrFail();

        return view('bio.show', ['page' => $bio]);
    }

    /**
     * Pro+ subdomain ({ws-slug}.nimu.li/b/{slug}) or verified custom domain.
     * Workspace resolved by ResolveWorkspaceBySubdomain middleware or host lookup here.
     */
    public function showScoped(string $slug, Request $request): View|Response
    {
        $host = $request->getHost();
        $apex = config('services.hetzner.zone', 'nimu.li');

        if (str_ends_with($host, '.'.$apex)) {
            $wsSlug = substr($host, 0, -(strlen($apex) + 1));
            $ws = Workspace::where('slug', $wsSlug)
                ->whereNotNull('subdomain_full')
                ->firstOrFail();

            abort_unless($ws->isPaidPlan(), 404);

            $bio = BioPage::where('workspace_id', $ws->id)
                ->where('subdomain_host', $host)
                ->where('slug', $slug)
                ->where('is_published', true)
                ->with('blocks')
                ->firstOrFail();
        } else {
            Domain::where('hostname', $host)
                ->where('scope', 'custom')
                ->whereNotNull('verified_at')
                ->firstOrFail();

            $bio = BioPage::where('subdomain_host', $host)
                ->where('slug', $slug)
                ->where('is_published', true)
                ->with('blocks')
                ->firstOrFail();
        }

        return view('bio.show', ['page' => $bio]);
    }

    public function preview(Workspace $workspace, string $bioUlid): View|Response
    {
        $bio = BioPage::where('ulid', $bioUlid)
            ->where('workspace_id', $workspace->id)
            ->with('blocks')
            ->firstOrFail();

        $editUrl = route('w.bio.edit', [$workspace->ulid, $bioUlid]);

        return view('bio.show', ['page' => $bio, 'isPreview' => true, 'editUrl' => $editUrl]);
    }
}
