<?php

namespace App\Http\Resources\Tenant;

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

class EmotionResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'tenant_id' => $this->tenant_id,
            'name' => $this->translatedText($this->name, 'Emotion'),
            'name_translations' => (array) $this->name,
            'description' => $this->description ? $this->translatedText($this->description, '') : null,
            'description_translations' => $this->description ? (array) $this->description : [],
            'icon' => $this->icon,
            'color' => $this->color,
            'sort_order' => $this->sort_order,
            'is_active' => (bool) $this->is_active,
            'is_global' => $this->tenant_id === null,
            'event_types' => $this->whenLoaded('eventTypes', function () {
                return $this->eventTypes->map(fn ($eventType) => [
                    'id' => $eventType->id,
                    'slug' => $eventType->slug,
                    'name' => $this->translatedText($eventType->name, $eventType->slug ?? ''),
                    'name_translations' => (array) $eventType->name,
                ]);
            }),
            'created_at' => optional($this->created_at)->toISOString(),
            'updated_at' => optional($this->updated_at)->toISOString(),
        ];
    }

    protected function translatedText(mixed $value, string $fallback): string
    {
        if (is_string($value) && $value !== '') {
            return $value;
        }

        if (! is_array($value)) {
            return $fallback;
        }

        $locale = app()->getLocale();
        $locales = array_filter([
            $locale,
            $locale && str_contains($locale, '-') ? explode('-', $locale)[0] : null,
            'de',
            'en',
        ]);

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

        $first = reset($value);
        return $first !== false ? (string) $first : $fallback;
    }
}
