<?php

namespace App\Http\Resources\Tenant;

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

class PhotoResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $tenantId = $request->attributes->get('tenant_id');
        $showSensitive = $this->event->tenant_id === $tenantId;
        $fullUrl = $this->getFullUrl();
        $thumbnailUrl = $this->getThumbnailUrl();

        return [
            'id' => $this->id,
            'filename' => $this->filename,
            'original_name' => $this->original_name,
            'mime_type' => $this->mime_type,
            'size' => (int) ($this->size ?? 0),
            'url' => $showSensitive ? ($fullUrl ?? $thumbnailUrl) : ($thumbnailUrl ?? $fullUrl),
            'thumbnail_url' => $thumbnailUrl ?? $fullUrl,
            'width' => $this->width,
            'height' => $this->height,
            'is_featured' => (bool) ($this->is_featured ?? false),
            'status' => $showSensitive ? $this->status : 'approved',
            'moderation_notes' => $showSensitive ? $this->moderation_notes : null,
            'likes_count' => (int) ($this->likes_count ?? $this->likes()->count()),
            'is_liked' => false,
            'uploaded_at' => $this->created_at->toISOString(),
            'uploader_name' => $this->guest_name ?? null,
            'ingest_source' => $this->ingest_source,
            'event' => [
                'id' => $this->event->id,
                'name' => $this->event->name,
                'slug' => $this->event->slug,
            ],
        ];
    }

    /**
     * Get full image URL
     */
    private function getFullUrl(): ?string
    {
        if (empty($this->filename)) {
            return null;
        }

        return url("storage/events/{$this->event->slug}/photos/{$this->filename}");
    }

    /**
     * Get thumbnail URL
     */
    private function getThumbnailUrl(): ?string
    {
        if (empty($this->filename)) {
            return null;
        }

        return url("storage/events/{$this->event->slug}/thumbnails/{$this->filename}");
    }
}
