<?php

declare(strict_types=1);

namespace App\Http\Resources;

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

class MediaItemResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        $fileUrl = $this->file_path ? url($this->file_path) : null;

        return [
            'id' => $this->id,
            'project_id' => $this->project_id,
            'type' => $this->type,
            'title' => $this->name,
            'name' => $this->name,
            'url' => $fileUrl,
            'thumbnail_url' => $fileUrl,
            'files' => $this->formatFiles($this->files),
            'category' => $this->whenLoaded('category', fn () => $this->category?->name),
            'subcategory' => $this->whenLoaded('subcategory', fn () => $this->subcategory?->name),
            'category_id' => $this->category_id,
            'subcategory_id' => $this->subcategory_id,
            'uploader_type' => $this->uploader_type,
            'uploader_display' => $this->uploader_display,
            'status' => $this->status,
            'description' => $this->description,
            'notes' => $this->notes,
            'tags' => $this->tags,
            'location_name' => $this->location_name,
            'gps' => $this->gps_lat && $this->gps_lng ? "{$this->gps_lat},{$this->gps_lng}" : null,
            'gps_lat' => $this->gps_lat,
            'gps_lng' => $this->gps_lng,
            'is_draft' => (bool) $this->is_draft,
            'document_category' => $this->document_category
                ?? ($this->relationLoaded('category') ? $this->category?->name : null),
            'valid_from' => $this->start_at?->toISOString(),
            'valid_until' => $this->end_at?->toISOString(),
            'start_at' => $this->start_at?->toISOString(),
            'end_at' => $this->end_at?->toISOString(),
            'document_number' => $this->contract_number,
            'contract_number' => $this->contract_number,
            'company_name' => $this->company_name,
            'company_phone' => $this->contact_phone,
            'contact_phone' => $this->contact_phone,
            'created_at_file' => $this->created_at_file?->toISOString(),
            'comment_count' => $this->whenCounted('comments'),
            'rating_avg' => $this->when(isset($this->ratings_avg_score), fn () => round((float) $this->ratings_avg_score, 2)),
            'created_at' => $this->created_at?->toISOString(),
            'updated_at' => $this->updated_at?->toISOString(),
            'project' => new ProjectResource($this->whenLoaded('project')),
        ];
    }

    private function formatFiles(?array $files): ?array
    {
        if ($files === null) {
            return null;
        }

        return array_map(
            fn ($file) => is_string($file) && ! str_starts_with($file, 'http') ? url($file) : $file,
            $files
        );
    }
}
