<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\ResourceCollection;

class SubscriptionCollection extends ResourceCollection
{
    /**
     * Transform the resource collection into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        // Group subscriptions by type for better organization
        $groupedSubscriptions = $this->collection->groupBy('subscribable_type');

        $result = [
            'stores' => [],
            'categories' => [],
            'brands' => [],
            'offers' => [],
            'total_count' => $this->collection->count(),
        ];

        foreach ($groupedSubscriptions as $type => $items) {
            switch ($type) {
                case 'App\\Models\\CountryStore':
                    $result['stores'] = $this->formatStoreSubscriptions($items, $request);
                    break;

                case 'App\\Models\\Category':
                    $result['categories'] = $this->formatCategorySubscriptions($items, $request);
                    break;

                case 'App\\Models\\Brand':
                    $result['brands'] = $this->formatBrandSubscriptions($items, $request);
                    break;

                case 'App\\Models\\Offer':
                    $result['offers'] = $this->formatOfferSubscriptions($items, $request);
                    break;
            }
        }

        return $result;
    }

    /**
     * Format store subscriptions
     */
    private function formatStoreSubscriptions($subscriptions, $request)
    {
        $locale = $this->getLocaleFromRequest($request);

        return $subscriptions->map(function ($subscription) use ($locale) {
            $store = $subscription->subscribable;
            if (!$store) return null;

            return [
                'subscription_id' => $subscription->id,
                'subscription_type' => $subscription->type,
                'subscribed_at' => $subscription->created_at,
                'store' => [
                    'id' => $store->id,
                    'country_id' => $store->country_id,
                    'store_id' => $store->store_id,
                    'name' => $store->store->getName($locale['locale_id']),
                    'description' => $store->store->getDescription($locale['locale_id']),
                    'country_name' => $store->country->getName($locale['language_id']),
                    'is_featured' => $store->is_featured,
                    'is_active' => $store->is_active,
                    'logo' => $store->store->getFirstMediaUrl('logo'),
                    'stats' => [
                        'followers_count' => $store->stats->followers_count ?? 0,
                        'offers_count' => $store->offers()->active()->count(),
                        'avg_discount' => $store->stats->avg_discount ?? 0,
                        'max_discount' => $store->stats->max_discount ?? 0,
                    ],
                ],
            ];
        })->filter()->values();
    }

    /**
     * Format category subscriptions
     */
    private function formatCategorySubscriptions($subscriptions, $request)
    {
        $locale = $this->getLocaleFromRequest($request);

        return $subscriptions->map(function ($subscription) use ($locale) {
            $category = $subscription->subscribable;
            if (!$category) return null;

            return [
                'subscription_id' => $subscription->id,
                'subscription_type' => $subscription->type,
                'subscribed_at' => $subscription->created_at,
                'category' => [
                    'id' => $category->id,
                    'name' => $category->getName($locale['language_id']),
                    'description' => $category->getDescription($locale['language_id']),
                    'is_featured' => $category->is_featured,
                    'is_active' => $category->is_active,
                    'icon' => $category->getFirstMediaUrl('icon'),
                    'cover' => $category->getFirstMediaUrl('cover'),
                    'offers_count' => $category->offers()->active()->count(),
                ],
            ];
        })->filter()->values();
    }

    /**
     * Format brand subscriptions
     */
    private function formatBrandSubscriptions($subscriptions, $request)
    {
        $locale = $this->getLocaleFromRequest($request);

        return $subscriptions->map(function ($subscription) use ($locale) {
            $brand = $subscription->subscribable;
            if (!$brand) return null;

            return [
                'subscription_id' => $subscription->id,
                'subscription_type' => $subscription->type,
                'subscribed_at' => $subscription->created_at,
                'brand' => [
                    'id' => $brand->id,
                    'name' => $brand->getName($locale['language_id']),
                    'description' => $brand->getDescription($locale['language_id']),
                    'is_featured' => $brand->is_featured,
                    'is_active' => $brand->is_active,
                    'logo' => $brand->getFirstMediaUrl('logo'),
                    'offers_count' => $brand->offers()->active()->count(),
                ],
            ];
        })->filter()->values();
    }

    /**
     * Format offer subscriptions
     */
    private function formatOfferSubscriptions($subscriptions, $request)
    {
        $locale = $this->getLocaleFromRequest($request);

        return $subscriptions->map(function ($subscription) use ($locale) {
            $offer = $subscription->subscribable;
            if (!$offer) return null;

            return [
                'subscription_id' => $subscription->id,
                'subscription_type' => $subscription->type,
                'subscribed_at' => $subscription->created_at,
                'offer' => [
                    'id' => $offer->id,
                    'title' => $offer->getTitle($locale['locale_id']),
                    'description' => $offer->getDescription($locale['locale_id']),
                    'type' => $offer->type,
                    'promotion_type' => $offer->promotion_type,
                    'discount_value' => $offer->discount_value,
                    'regular_price' => $offer->regular_price,
                    'sale_price' => $offer->sale_price,
                    'is_featured' => $offer->is_featured,
                    'is_active' => $offer->is_active,
                    'is_expired' => $offer->is_expired,
                    'expires_at' => $offer->expires_at,
                    'image' => $offer->getFirstMediaUrl('images'),
                    'store_name' => $offer->countryStore->store->getName($locale['locale_id']),
                    'brand_name' => $offer->brand ? $offer->brand->getName($locale['language_id']) : null,
                ],
            ];
        })->filter()->values();
    }

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

    /**
     * Add additional meta information
     */
    public function with($request)
    {
        $groupedSubscriptions = $this->collection->groupBy('subscribable_type');

        return [
            'meta' => [
                'counts' => [
                    'stores' => $groupedSubscriptions->get('App\\Models\\CountryStore', collect())->count(),
                    'categories' => $groupedSubscriptions->get('App\\Models\\Category', collect())->count(),
                    'brands' => $groupedSubscriptions->get('App\\Models\\Brand', collect())->count(),
                    'offers' => $groupedSubscriptions->get('App\\Models\\Offer', collect())->count(),
                ],
                'by_subscription_type' => [
                    'follows' => $this->collection->where('type', 'follow')->count(),
                    'notifications' => $this->collection->where('type', 'notify')->count(),
                    'favorites' => $this->collection->where('type', 'favorite')->count(),
                ],
                'latest_subscription' => $this->collection->sortByDesc('created_at')->first()?->created_at,
            ],
        ];
    }
}