<?php

namespace App\Http\Resources;

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

class ProductResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        $videoUrl = null;
        if ($this->video_path) {
            $path = Storage::disk('public')->url($this->video_path);
            if (str_starts_with($path, 'http://') || str_starts_with($path, 'https://')) {
                $videoUrl = $path;
            } else {
                $baseUrl = $request ? rtrim($request->getSchemeAndHttpHost(), '/') : rtrim(config('app.url'), '/');
                $videoUrl = $baseUrl . '/' . ltrim($path, '/');
            }
        }

        return [
            'id' => $this->id,
            'name' => $this->name,
            'slug' => $this->slug,
            'description' => $this->description,
            'short_description' => $this->short_description,
            'sku' => $this->sku,
            'category_id' => $this->category_id,
            'base_price' => $this->base_price,
            'discount_price' => $this->discount_price,
            'min_price' => $this->min_price,
            'max_price' => $this->max_price,
            'total_stock' => $this->total_stock,
            'is_active' => $this->is_active,
            'is_featured' => $this->is_featured,
            'sort_order' => $this->sort_order,
            'meta' => $this->meta,
            'average_rating' => $this->average_rating ? round($this->average_rating, 1) : null,
            'ratings_count' => $this->ratings_count ?? 0,
            'video_path' => $this->video_path,
            'video_url' => $videoUrl,
            'category' => $this->whenLoaded('category', fn () => new CategoryResource($this->category)),
            'images' => $this->whenLoaded('images', fn () => ProductImageResource::collection($this->images)),
            'variants' => $this->whenLoaded('variants', fn () => ProductVariantResource::collection($this->variants)),
            'reviews' => $this->whenLoaded('productRatings', fn () => ProductReviewResource::collection($this->productRatings)),
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}
