<?php

namespace Modules\Feedback\Transformers;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Modules\Feedback\Entities\Feedback;

class FeedbackResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'type' => $this->type,
            'title' => $this->title,
            'description' => $this->description,
            'priority' => $this->priority,
            'status' => $this->status,
            'page_url' => $this->page_url,
            'browser_info' => $this->browser_info,
            'images' => $this->whenLoaded('documents', function () {
                return $this->documents
                    ->where('type', Feedback::IMAGE_DOCUMENT_TYPE)
                    ->values()
                    ->map(fn ($document) => $this->formatDocument($document));
            }),
            'videos' => $this->whenLoaded('documents', function () {
                return $this->documents
                    ->where('type', Feedback::VIDEO_DOCUMENT_TYPE)
                    ->values()
                    ->map(fn ($document) => $this->formatDocument($document));
            }),
            'steps_to_reproduce' => $this->steps_to_reproduce,
            'expected_behavior' => $this->expected_behavior,
            'actual_behavior' => $this->actual_behavior,
            'additional_notes' => $this->additional_notes,
            'admin_notes' => $this->admin_notes,
            'resolved_at' => $this->resolved_at,
            'user' => $this->whenLoaded('user', function () {
                return [
                    'id' => $this->user->id,
                    'name' => $this->user->name,
                    'email' => $this->user->email,
                    'army_number' => $this->user->army_number,
                ];
            }),
            'assigned_user' => $this->whenLoaded('assignedUser', function () {
                return [
                    'id' => $this->assignedUser->id,
                    'name' => $this->assignedUser->name,
                    'email' => $this->assignedUser->email,
                ];
            }),
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }

    protected function formatDocument($document): array
    {
        return [
            'id' => $document->id,
            'name' => $document->name,
            'mime_type' => $document->mime_type,
            'file_size' => $document->file_size,
            'type' => $document->type,
            'url' => url(route('feedback.download-document', [
                'id' => $this->id,
                'documentId' => $document->id,
            ])),
        ];
    }
}
