<?php

namespace App\Http\Controllers\Api\V1\Product\Resources;

use App\Http\Resources\MediaResource;
use App\Repositories\Ecommerce\Product\Property\PropertyRepository;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class ProductIndexResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  Request  $request
     * @return array|Arrayable|\JsonSerializable
     */
    public function toArray($request): array
    {
        $reviews = $this->whenLoaded('reviews');

        return [
            'id' => $this->id,
            'parent_id' => $this->parent_id,

            'name' => $this->name,
            'slug' => $this->slug,
            'description' => '',

            'sku' => $this->sku,
            'barcode' => $this->barcode,
            'stock' => $this->stock,

            'price_amount' => $this->price_amount,
            'old_price_amount' => $this->old_price_amount,

            'backorder' => $this->backorder,
            'weight_value' => $this->weight_value,
            'weight_unit' => $this->weight_unit,
            'height_value' => $this->height_value,
            'height_unit' => $this->height_unit,

            'media' => MediaResource::collection($this->whenLoaded('media')),

            'created_at' => $this->created_at,

            'seo_title' => $this->seo_title,
            'seo_description' => $this->seo_description,

            'colour' => PropertyRepository::getRealValue('colour', $this->colour),
            'size' => PropertyRepository::getRealValue('size', $this->size),

            'brand' => [
                'id' => $this->brand_id,
                'name' => $this->brand?->name,
            ],

            'reviews' => [
                'count' => $reviews ? $reviews->count() : 0,
                'rating' => $reviews ? number_format($reviews->avg('rating'), 2) : 0,
            ],
        ];
    }
}
