<?php

declare(strict_types=1);

namespace App\Http\Resources;

use App\Enums\Status;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class PostResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return [
            'breadcrumbs' => $this->breadcrumbs,
            'create_by' => $this->create_by,
            'created_at' => $this->created_at,
            'desc' => html_entity_decode($this->desc, ENT_HTML5, 'UTF-8'),
            'excerpt' => $this->excerpt,
            'gallery' => $this->formatFiles($this->gallery),
            'image' => $this->image ? url($this->image) : null,
            'is_featured' => $this->is_featured,
            'meta_desc' => $this->meta_desc,
            'meta_keywords' => $this->meta_keywords,
            'meta_title' => $this->meta_title,
            'slug' => $this->slug,
            'status' => Status::from((int) $this->status)?->label(),
            'time_to_read' => $this->time_to_read,
            'title' => $this->title,
            'type' => $this->type,
            'update_by' => $this->update_by,
            'updated_at' => $this->updated_at,
            'video' => $this->video ? url($this->video) : null,
            'view_count' => $this->view_count,

            'author' => UserResource::make($this->author),
            'categories' => CategoryResource::collection($this->categories),
            'tags' => TagResource::collection($this->tags),
        ];
    }

    /**
     * @param  array<int, string>|null  $files
     * @return array<int, string>|null
     */
    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
        );
    }
}
