<?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 SupportTicketResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'code' => $this->code,
            'user_id' => $this->user_id,
            'category' => $this->category,
            'category_label' => SupportTicket::categoryOptions()[(string) $this->category] ?? $this->category,
            'title' => $this->title,
            'body' => $this->body,
            'status' => $this->status,
            'status_label' => SupportTicket::statusOptions()[(string) $this->status] ?? $this->status,
            'attachments' => $this->formatFiles($this->attachments),
            'close_reason' => $this->when($this->status === SupportTicket::STATUS_CLOSED, $this->close_reason),
            'closed_at' => $this->closed_at?->toISOString(),
            'replies_count' => $this->whenCounted('replies'),
            'created_at' => $this->created_at?->toISOString(),
            'updated_at' => $this->updated_at?->toISOString(),
            'user' => new UserResource($this->whenLoaded('user')),
            'replies' => SupportTicketReplyResource::collection($this->whenLoaded('replies')),
        ];
    }

  /**
   * @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
        )));
    }
}
