<?php

declare(strict_types=1);

namespace App\Http\Resources;

use App\Models\SupportTicket;
use App\Support\FileUrl;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class SupportTicketReplyResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'support_ticket_id' => $this->support_ticket_id,
            'body' => $this->body,
            'is_admin' => (bool) $this->is_admin,
            'attachments' => $this->formatFiles($this->attachments),
            'edited_at' => $this->edited_at?->toISOString(),
            'created_at' => $this->created_at?->toISOString(),
            'user' => new UserResource($this->whenLoaded('user')),
        ];
    }

  /**
   * @param  array<int, string>|null  $files
   * @return array<int, string>|null
   */
    private function formatFiles(?array $files): ?array
    {
        if ($files === null) {
            return null;
        }

        return array_values(array_filter(array_map(
            fn (string $file): ?string => FileUrl::url($file),
            $files
        )));
    }
}
