<?php
namespace App\Http\Resources;

use App\Services\Maturity\ArtworkMaturityService;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Http\Resources\MissingValue;
use App\Services\ThumbnailService;
use Illuminate\Support\Str;

class ArtworkListResource extends JsonResource
{
    /**
     * Transform the resource into an array for listings (browse feed).
     */
    public function toArray($request): array
    {
        if ($this instanceof MissingValue || $this->resource instanceof MissingValue) {
            return [];
        }
        // Safe accessor to avoid magic __get which may trigger MissingValue errors
        $get = function ($key) {
            $r = $this->resource;
            if ($r instanceof MissingValue || $r === null) {
                return null;
            }
            if (method_exists($r, 'getAttribute')) {
                return $r->getAttribute($key);
            }
            if (is_array($r)) {
                return $r[$key] ?? null;
            }
            if (is_object($r)) {
                return $r->{$key} ?? null;
            }
            return null;
        };
        $primaryCategory = $this->whenLoaded('categories', function () {
            return $this->categories->sortBy('sort_order')->first();
        });

        // Normalize MissingValue into null so later checks are straightforward
        if ($primaryCategory instanceof MissingValue) {
            $primaryCategory = null;
        }

        $contentTypeSlug = null;
        $contentTypeName = null;
        $categoryPath = null;
        if ($primaryCategory) {
            $contentTypeSlug = optional($primaryCategory->contentType)->slug ?? null;
            $contentTypeName = optional($primaryCategory->contentType)->name ?? null;
            $categoryPath = $primaryCategory->full_slug_path ?? null;
        }
        $slugVal = $get('slug');
        $hash = (string) ($get('hash') ?? '');
        $thumbExt = (string) ($get('thumb_ext') ?? '');
        $canonicalSlug = Str::slug((string) ($slugVal ?: $get('title') ?: 'artwork'));
        if ($canonicalSlug === '') {
            $canonicalSlug = (string) ($get('id') ?? 'artwork');
        }
        $webUrl = $contentTypeSlug && $categoryPath && $slugVal
            ? '/' . strtolower($contentTypeSlug) . '/' . strtolower($categoryPath) . '/' . $slugVal
            : null;

        $artId = $get('id');
        $directUrl = $artId ? '/art/' . $artId . '/' . $canonicalSlug : null;

        $decode = static fn (?string $v): string => html_entity_decode((string) ($v ?? ''), ENT_QUOTES | ENT_HTML5, 'UTF-8');

        $group = $this->relationLoaded('group') ? $this->group : null;
        $user = $this->relationLoaded('user') ? $this->user : null;
        $isGroupPublisher = $group !== null;
        $publisher = ($group || $user)
            ? [
                'type' => $isGroupPublisher ? 'group' : 'user',
                'id' => (int) ($isGroupPublisher ? $group?->id : $user?->id),
                'name' => $decode($isGroupPublisher ? $group?->name : $user?->name),
                'username' => $isGroupPublisher ? '' : (string) ($user?->username ?? ''),
                'avatar_url' => $isGroupPublisher ? $group?->avatarUrl() : $user?->profile?->avatar_url,
                'profile_url' => $isGroupPublisher
                    ? $group?->publicUrl()
                    : (! empty($user?->username) ? '/@' . $user->username : null),
            ]
            : null;

        return app(ArtworkMaturityService::class)->decoratePayload([
            'id' => $artId,
            'slug' => $slugVal,
            'title' => $decode($get('title')),
            'description' => $this->when($request->boolean('include_description'), fn() => $decode($get('description'))),
            'dimensions' => [
                'width' => $get('width'),
                'height' => $get('height'),
            ],
            'thumbnail_url' => $this->when(! empty($hash) && ! empty($thumbExt), fn() => ThumbnailService::fromHash($hash, $thumbExt, 'md')),
            'author' => $publisher,
            'publisher' => $publisher,
            'author_name' => $publisher['name'] ?? '',
            'avatar_url' => $publisher['avatar_url'] ?? null,
            'profile_url' => $publisher['profile_url'] ?? null,
            'published_as_type' => $publisher['type'] ?? null,
            'category' => $primaryCategory ? [
                'slug' => $primaryCategory->slug ?? null,
                'name' => $decode($primaryCategory->name ?? null),
                'content_type' => $contentTypeSlug,
                'content_type_slug' => $contentTypeSlug,
                'content_type_name' => $decode($contentTypeName),
                'url' => $webUrl,
            ] : null,
            'canonical_url' => $directUrl,
            'urls' => [
                'web' => $webUrl ?? $directUrl,
                'direct' => $directUrl,
                'canonical' => $directUrl ?? $webUrl,
            ],
        ], $this->resource, $request->user());
    }
}
