<?php

namespace App\Http\Controllers;

use App\Models\Development;
use App\Models\ProjectMedium;
use Illuminate\Support\Facades\Storage;
use Inertia\Inertia;
use Inertia\Response;

/** The public portal lists the projects that have been published from the admin. */
class PortalHomeController extends Controller
{
    public function __invoke(): Response
    {
        $developments = Development::query()
            ->where('published', true)
            ->with(['media', 'lots:id,development_id,block,status,area,price'])
            ->orderByDesc('published_at')
            ->get();

        return Inertia::render('portal/index', [
            'developments' => $developments->map(function (Development $development): array {
                $available = $development->lots->where('status', 'available');
                $cover = $this->cover($development);

                return [
                    'id' => (string) $development->id,
                    'name' => $development->name,
                    'slug' => $development->slug,
                    'location' => $development->location,
                    'headline' => $development->headline ?? 'Lotes con inventario verificado desde el plano.',
                    'availableLots' => $available->count(),
                    'soldLots' => $development->lots->where('status', 'sold')->count(),
                    'heldLots' => $development->lots->where('status', 'held')->count(),
                    'totalLots' => $development->lots->count(),
                    'blockCount' => $development->lots->pluck('block')->filter()->unique()->count(),
                    'startingPrice' => (float) ($available->where('price', '>', 0)->min('price') ?? 0),
                    'smallestArea' => (float) ($available->min('area') ?? 0),
                    'largestArea' => (float) ($available->max('area') ?? 0),
                    'coverUrl' => $cover?->url() ?? ($development->source_image_path
                        ? Storage::disk('public')->url($development->source_image_path)
                        : null),
                    'coverKind' => $cover === null ? 'image' : $cover->kind,
                    'coverPlaysInline' => $cover !== null && $cover->playsInline(),
                    'mediaCount' => $development->media->count(),
                ];
            })->values(),
        ]);
    }

    /** The chosen cover, or the first image if the project has not picked one. */
    private function cover(Development $development): ?ProjectMedium
    {
        foreach ($development->media as $medium) {
            if ($medium->is_cover) {
                return $medium;
            }
        }

        foreach ($development->media as $medium) {
            if ($medium->isImage()) {
                return $medium;
            }
        }

        return null;
    }
}
