<?php

namespace App\Domain\Website\Services;

use App\Domain\Shared\Models\Academy;
use App\Domain\Website\Models\WebsiteBlock;
use Illuminate\Support\Collection;

/**
 * Supplies live ERP records to data-bound blocks.
 *
 * Keeping this out of the Blade partials means a block template never queries;
 * it just receives `$items`. That also makes the builder preview and the public
 * site render identically.
 */
class BlockDataResolver
{
    public function __construct(
        private readonly WebsiteDataService $data,
    ) {}

    /** @return Collection<int,mixed> */
    public function for(WebsiteBlock $block, array $context = []): Collection
    {
        $academy = $context['academy'] ?? null;

        if (! $academy instanceof Academy) {
            return collect();
        }

        $limit = (int) ($block->get('limit') ?: 0);

        $items = match ($block->type) {
            'data_branches' => $this->data->getBranches($academy),
            'data_programs' => $this->data->getPrograms($academy),
            'data_activities' => $this->data->getActivities($academy),
            'data_news' => $this->data->getNews($academy, $limit ?: 6),
            'data_testimonials' => $this->data->getTestimonials($academy, $limit ?: 10),
            'gallery' => $block->get('source') === 'collection'
                ? $this->data->getGalleryImages($academy, $limit ?: 12)
                : collect($block->get('images') ?: []),
            'logo_strip' => $block->get('use_partner_data', true)
                ? $this->data->getPartners($academy)
                : collect($block->get('logos') ?: []),
            'accordion' => $block->get('use_faq_data')
                ? $this->data->getFaqs($academy)
                : collect($block->get('items') ?: []),
            default => collect($this->manualItems($block)),
        };

        $items = collect($items);

        return $limit > 0 ? $items->take($limit) : $items;
    }

    /** Repeater-backed blocks simply expose their own rows as $items. */
    private function manualItems(WebsiteBlock $block): array
    {
        foreach (['items', 'plans', 'logos', 'links', 'locations', 'products'] as $key) {
            $rows = $block->get($key);
            if (is_array($rows) && $rows !== []) {
                return $rows;
            }
        }

        return [];
    }
}
