<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class ProductResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'category_id' => $this->category_id,
            'category_name' => $this->category?->name,
            'category_slug' => $this->category?->slug,
            'parent_category_name' => $this->category?->parent?->name,
            'parent_category_slug' => $this->category?->parent?->slug,
            'name' => $this->name,
            'slug' => $this->slug,
            'sku' => $this->sku,
            'short_description' => $this->short_description,
            'description' => $this->description,
            'price' => $this->price !== null ? (float) $this->price : null,
            'price_on_request' => (bool) $this->price_on_request,
            'availability' => $this->availability,
            'stock_status' => $this->stock_status,
            'featured' => (bool) $this->featured,
            'new_arrival' => (bool) $this->new_arrival,
            'best_seller' => (bool) $this->best_seller,
            'editor_pick' => (bool) $this->editor_pick,
            'status' => $this->status,
            'material' => $this->material,
            'color' => $this->color,
            'finish' => $this->finish,
            'dimensions' => $this->dimensions,
            'weight' => $this->weight,
            'care_instructions' => $this->care_instructions,
            'shipping_information' => $this->shipping_information,
            'seo_title' => $this->seo_title,
            'seo_description' => $this->seo_description,
            'images' => $this->images->map(function ($img) {
                return [
                    'id' => $img->id,
                    'image_path' => $img->image_path,
                    'sort_order' => $img->sort_order,
                    'is_primary' => (bool) $img->is_primary,
                ];
            }),
            'primary_image' => $this->primaryImage?->image_path ?? ($this->images->first()?->image_path ?? null),
            'variants' => $this->variants->map(function ($v) {
                return [
                    'id' => $v->id,
                    'name' => $v->name,
                    'sku' => $v->sku,
                    'price' => $v->price !== null ? (float) $v->price : null,
                    'stock_status' => $v->stock_status,
                    'attributes' => $v->attributes,
                ];
            }),
            'reviews' => ReviewResource::collection($this->whenLoaded('reviews')),
            'reviews_avg_rating' => (float) ($this->reviews()->avg('rating') ?? 5.0),
            'reviews_count' => (int) $this->reviews()->count(),
            'created_at' => $this->created_at?->toIso8601String(),
        ];
    }
}
