<?php

namespace App\Http\Resources\Tenant;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class TaskResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $assignedEventsCount = $this->relationLoaded('assignedEvents')
            ? $this->assignedEvents->count()
            : $this->assignedEvents()->count();

        $titleTranslations = $this->normalizeTranslations($this->title);
        $descriptionTranslations = $this->normalizeTranslations($this->description, allowNull: true);
        $exampleTranslations = $this->normalizeTranslations($this->example_text, allowNull: true);

        return [
            'id' => $this->id,
            'tenant_id' => $this->tenant_id,
            'slug' => $this->slug,
            'title' => $this->translatedText($titleTranslations, 'Untitled task'),
            'title_translations' => $titleTranslations,
            'description' => $descriptionTranslations ? $this->translatedText($descriptionTranslations, '') : null,
            'description_translations' => $descriptionTranslations ?? [],
            'example_text' => $exampleTranslations ? $this->translatedText($exampleTranslations, '') : null,
            'example_text_translations' => $exampleTranslations ?? [],
            'priority' => $this->priority,
            'difficulty' => $this->difficulty,
            'due_date' => $this->due_date?->toISOString(),
            'is_completed' => (bool) $this->is_completed,
            'event_type_id' => $this->event_type_id,
            'event_type' => $this->whenLoaded(
                'eventType',
                fn () => new EventTypeResource($this->eventType)
            ),
            'emotion_id' => $this->emotion_id,
            'emotion' => $this->whenLoaded(
                'emotion',
                fn () => [
                    'id' => $this->emotion->id,
                    'name' => $this->translatedText($this->normalizeTranslations($this->emotion->name), ''),
                    'name_translations' => $this->emotion->name,
                    'icon' => $this->emotion->icon,
                    'color' => $this->emotion->color,
                ]
            ),
            'collection_id' => $this->collection_id,
            'source_task_id' => $this->source_task_id,
            'source_collection_id' => $this->source_collection_id,
            'sort_order' => $this->pivot?->sort_order,
            'assigned_events_count' => $assignedEventsCount,
            'assigned_events' => $this->whenLoaded(
                'assignedEvents',
                fn () => EventResource::collection($this->assignedEvents)
            ),
            'created_at' => $this->created_at?->toISOString(),
            'updated_at' => $this->updated_at?->toISOString(),
        ];
    }

    /**
     * @return array<string, string>|null
     */
    protected function normalizeTranslations(mixed $value, bool $allowNull = false): ?array
    {
        if ($allowNull && ($value === null || $value === '')) {
            return null;
        }

        if (is_array($value)) {
            $filtered = array_filter(
                $value,
                static fn ($text) => is_string($text) && $text !== ''
            );

            return ! empty($filtered)
                ? $filtered
                : ($allowNull ? null : []);
        }

        if (is_string($value) && $value !== '') {
            $locale = app()->getLocale() ?: 'de';

            return [
                $locale => $value,
            ];
        }

        return $allowNull ? null : [];
    }

    /**
     * @param  array<string, string>  $translations
     */
    protected function translatedText(array $translations, string $fallback): string
    {
        $locale = app()->getLocale();
        $locales = array_filter([
            $locale,
            $locale && str_contains($locale, '-') ? explode('-', $locale)[0] : null,
            'de',
            'en',
        ]);

        foreach ($locales as $code) {
            if ($code && isset($translations[$code]) && $translations[$code] !== '') {
                return $translations[$code];
            }
        }

        $first = reset($translations);

        return $first !== false ? $first : $fallback;
    }
}
