<?php

namespace App\Http\Resources;

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

class StoreResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        $locale = $this->getLocaleFromRequest($request);
        
        return [
            'id' => $this->id,
            'store_id' => $this->store_id,
            'name' => $this->store->getName($locale['locale_id']),
            'description' => $this->store->getDescription($locale['locale_id']),
            'is_featured' => $this->is_featured,
            'is_active' => $this->is_active,
            'order' => $this->order,
            'logo' => $this->store->getFirstMediaUrl('logo'),
            'gallery' => $this->when(
                $this->relationLoaded('store') && $this->store->hasMedia('gallery'),
                fn() => $this->store->getMedia('gallery')->map(fn($media) => $media->getUrl())
            ),
            'offers_count' => $this->whenCounted('offers'),
            'stats' => $this->when($this->relationLoaded('stats'), [
                'followers_count' => $this->stats->followers_count ?? 0,
                'uses_count' => $this->stats->uses_count ?? 0,
                'views_count' => $this->stats->views_count ?? 0,
                'popularity' => $this->stats->popularity ?? 0,
                'avg_discount' => round($this->stats->avg_discount ?? 0, 2),
                'max_discount' => round($this->stats->max_discount ?? 0, 2),
            ]),
            'categories' => CategoryResource::collection($this->whenLoaded('categories')),
            'is_subscribed' => $this->when(
                $request->user(), 
                fn() => $request->user()->isSubscribedTo($this->resource, 'follow')
            ),
        ];
    }

    /**
     * Get locale from request attributes
     */
    private function getLocaleFromRequest(Request $request): array
    {
        return [
            'country_id' => $request->attributes->get('country_id'),
            'language_id' => $request->attributes->get('language_id'),
            'locale_id' => $request->attributes->get('locale_id'),
        ];
    }
}