<?php

namespace App\Services\Content;

use App\Models\ContentEntry;
use App\Models\ContentType;
use App\Services\Schema\LocaleResolver;
use Illuminate\Support\Facades\Cache;

class ContentDeliveryService
{
    /**
     * ✅ GET SINGLE SLUG (same behavior you already have)
     * Returns:
     * [
     *   'contentType' => {...},
     *   'data' => {...} OR [...]
     * ]
     */
    public function getPublic(string $slug, string $locale, ?string $fallback = null): array
    {
        $type = ContentType::where('slug', $slug)->firstOrFail();

        $fallback = $fallback ?: ($type->default_locale ?: 'en');
        $cacheKey = app(ContentCache::class)->key($slug, $locale, $fallback);

        return Cache::remember($cacheKey, now()->addMinutes(30), function () use ($type, $locale, $fallback) {
            $resolver = app(LocaleResolver::class);

            if ($type->is_single) {
                $entry = ContentEntry::where('content_type_id', $type->id)
                    ->where('status', 'published')
                    ->latest()
                    ->first();

                $data = $entry?->data
                    ? $resolver->resolveData($type->schema, $entry->data, $locale, $fallback)
                    : null;

                return [
                    'contentType' => $this->typeMeta($type),
                    'data' => $data,
                ];
            }

            $entries = ContentEntry::where('content_type_id', $type->id)
                ->where('status', 'published')
                ->latest()
                ->get();

            $list = $entries->map(function ($e) use ($resolver, $type, $locale, $fallback) {
                return $resolver->resolveData($type->schema, $e->data ?? [], $locale, $fallback);
            })->values();

            return [
                'contentType' => $this->typeMeta($type),
                'data' => $list,
            ];
        });
    }

    /**
     * ✅ GET ALL CONTENT ONCE
     * Returns map:
     * [
     *   "home"   => {...fields...},   // single type
     *   "footer" => {...fields...},   // single type
     *   "blog"   => [ {...}, {...} ]  // list type
     * ]
     */
    public function getPublicAll(string $locale, ?string $fallback = null): array
    {
        // ✅ one cache key for all
        $fb = $fallback ?: 'auto';
        $cacheKey = app(ContentCache::class)->key('__all__', $locale, $fb);

        return Cache::remember($cacheKey, now()->addMinutes(30), function () use ($locale, $fallback) {
            $resolver = app(LocaleResolver::class);

            // ✅ Fetch all content types (add filter if you have "is_public" or similar)
            $types = ContentType::query()->get();

            if ($types->isEmpty()) return [];

            // ✅ Fetch all published entries for these types in ONE query
            $entries = ContentEntry::query()
                ->whereIn('content_type_id', $types->pluck('id'))
                ->where('status', 'published')
                ->orderByDesc('created_at')
                ->get();

            $entriesByType = $entries->groupBy('content_type_id');

            $result = [];

            foreach ($types as $type) {
                $fb = $fallback ?: ($type->default_locale ?: 'en');

                $group = $entriesByType->get($type->id, collect());

                // ✅ single type -> latest entry only
                if ($type->is_single) {
                    $entry = $group->first();

                    $data = $entry?->data
                        ? $resolver->resolveData($type->schema, $entry->data, $locale, $fb)
                        : null;

                    // 🔥 store directly by slug
                    $result[$type->slug] = $data;
                    continue;
                }

                // ✅ collection type -> list
                $list = $group->map(function ($e) use ($resolver, $type, $locale, $fb) {
                    return $resolver->resolveData($type->schema, $e->data ?? [], $locale, $fb);
                })->values();

                $result[$type->slug] = $list;
            }

            return $result;
        });
    }

    private function typeMeta(ContentType $type): array
    {
        return [
            'name' => $type->name,
            'slug' => $type->slug,
            'is_single' => (bool) $type->is_single,
            'locales' => $type->locales,
            'default_locale' => $type->default_locale,
        ];
    }
}
