<?php

namespace App\Http\Controllers;

use App\Models\Development;
use App\Models\Lot;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Inertia\Inertia;
use Inertia\Response;

/**
 * The public masterplan: the same interactive plan the studio produces, with
 * the commercial data a buyer needs on each lot.
 */
class PortalExplorerController extends Controller
{
    public function __invoke(Request $request): Response
    {
        $slug = Str::slug((string) $request->query('project', ''));

        $development = Development::query()
            ->where('published', true)
            ->with('lots')
            ->when($slug !== '', fn ($query) => $query->where('slug', $slug))
            ->when($slug === '', fn ($query) => $query->whereHas('lots')->orderByDesc('published_at'))
            ->first();

        if ($development === null || $development->plan_frame === null) {
            return Inertia::render('portal/explorer', [
                'project' => null,
                'frame' => null,
                'basePlanUrl' => null,
                'lots' => [],
                'projects' => $this->publishedProjects(),
            ]);
        }

        return Inertia::render('portal/explorer', [
            'project' => [
                'name' => $development->name,
                'slug' => $development->slug,
                'location' => $development->location,
                'headline' => $development->headline,
                'projectUrl' => route('portal.project', $development->slug),
                'whatsapp' => $development->whatsappNumber(),
                'downPaymentPercent' => $development->down_payment_percent,
                'financingMonths' => $development->financing_months,
            ],
            'frame' => $development->plan_frame,
            'basePlanUrl' => $development->source_image_path
                ? Storage::disk('public')->url($development->source_image_path)
                : null,
            'lots' => $development->lots->map(fn (Lot $lot): array => [
                'databaseId' => $lot->id,
                'id' => $lot->external_id,
                'lot' => 'L-'.$lot->lot_number,
                'lotNumber' => $lot->lot_number,
                'block' => $lot->block === null ? null : str_replace('MZ-', '', $lot->block),
                'blockLabel' => $lot->block,
                'area' => (float) $lot->area,
                'areaRaw' => $lot->area_raw,
                'dimensions' => array_map(
                    static fn (array $measurement): string => (string) ($measurement['text'] ?? ''),
                    $lot->measurements ?? [],
                ),
                'status' => $lot->status,
                'statusEvidence' => null,
                'statusConfidence' => null,
                'polygon' => $lot->points,
                'labelPoint' => $lot->label_point,
                'confidence' => null,
                'pass' => null,
                'needsReview' => false,
                'note' => '',
                'price' => (float) $lot->price,
                'orientation' => $lot->orientation,
                'financing' => $lot->financing,
            ])->values(),
            'projects' => $this->publishedProjects(),
        ]);
    }

    /** @return list<array{name: string, slug: string}> */
    private function publishedProjects(): array
    {
        $projects = [];

        foreach (Development::query()->where('published', true)->orderBy('name')->get(['name', 'slug']) as $development) {
            $projects[] = ['name' => $development->name, 'slug' => $development->slug];
        }

        return $projects;
    }
}
