<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;

class Media extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function getExtension($data){

        $fileInfo = pathinfo($data);
        $extension = $fileInfo['extension'];
        return $extension;

    }

    public function convertBitsToReadableSize($size) {
        // Define size units
        $units = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
        
        // Convert bits to bytes
        $sizeInBytes = $size;
        
        // Determine the appropriate unit
        for ($i = 0; $sizeInBytes >= 1024 && $i < count($units) - 1; $i++) {
            $sizeInBytes /= 1024;
        }
        
        // Return the human-readable size with the unit
        return round($sizeInBytes, 2) . ' ' . $units[$i];
    }

    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'path' => $this->path,
            'thumb_path' => url(Storage::url($this->thumb_path)),
            'webp_path' => url(Storage::url($this->webp_path)),
            'orignal_size' => $this->orignal_size,
            'file_extension' => $this->getExtension($this->webp_path),
            'thumb_size' => $this->convertBitsToReadableSize($this->webp_size),
            'user_id' => $this->user_id,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at
        ];
    }
}