<?php

namespace App\Services;

use App\Models\Product;
use Illuminate\Database\Eloquent\Collection;

class ProductComparisonService
{
    public function compare(Collection $products): array
    {
        if ($products->isEmpty()) {
            return [];
        }

        return [
            'products' => $products->map(fn ($p) => $this->formatProductForComparison($p)),
            'analysis' => [
                'best_value' => $this->rankByValue($products)->first(),
                'highest_quality' => $this->rankByQuality($products)->first(),
                'lowest_price' => $products->sortBy('price')->first(),
                'highest_discount' => $products->sortByDesc('discount')->first(),
                'most_popular' => $products->sortByDesc('sales_180day')->first(),
            ],
            'price_range' => [
                'min' => $products->min('price'),
                'max' => $products->max('price'),
                'avg' => $products->avg('price'),
            ],
            'comparison_matrix' => $this->buildComparisonMatrix($products),
        ];
    }

    public function rankByQuality(Collection $products): Collection
    {
        return $products->sortByDesc(function ($product) {
            return ($product->positive_feedback * 0.6) +
                   ($product->sales_180day * 0.4);
        })->values();
    }

    public function rankByValue(Collection $products): Collection
    {
        return $products->sortByDesc(function ($product) {
            $discountPercent = $product->discount > 0 ? $product->discount : 0;

            return ($product->positive_feedback * 0.5) +
                   ($discountPercent * 0.3) +
                   ($product->sales_180day * 0.2);
        })->values();
    }

    public function determineBestChoice(Collection $products, array $userPreferences = []): ?Product
    {
        if ($products->isEmpty()) {
            return null;
        }

        $weights = array_merge([
            'price_importance' => 0.3,
            'quality_importance' => 0.4,
            'discount_importance' => 0.2,
            'popularity_importance' => 0.1,
        ], $userPreferences);

        return $products->sortByDesc(function ($product) use ($weights) {
            $score = 0;

            $priceScore = ($product->price) > 0
                ? (1 / $product->price) * 100
                : 0;
            $score += $priceScore * $weights['price_importance'];

            $score += $product->positive_feedback * $weights['quality_importance'];

            $discountScore = $product->discount ?? 0;
            $score += $discountScore * $weights['discount_importance'];

            $popularityScore = $product->sales_180day ?? 0;
            $score += $popularityScore * $weights['popularity_importance'];

            return $score;
        })->first();
    }

    protected function formatProductForComparison(Product $product): array
    {
        return [
            'id' => $product->id,
            'name' => $product->name_en ?? $product->name_ar,
            'price' => $product->price,
            'discount_price' => $product->discount_price,
            'discount' => $product->discount,
            'rating' => $product->positive_feedback,
            'sales' => $product->sales_180day,
            'category' => $product->category?->name_en ?? $product->category?->name_ar,
            'features' => $this->extractKeyFeatures($product),
        ];
    }

    protected function extractKeyFeatures(Product $product): array
    {
        return [
            'has_discount' => $product->discount > 0,
            'has_promo_code' => ! empty($product->code_name),
            'commission_rate' => $product->direct_commission_rate,
            'video_available' => ! empty($product->video_url),
        ];
    }

    protected function buildComparisonMatrix(Collection $products): array
    {
        return [
            'prices' => $products->pluck('price', 'id')->toArray(),
            'discounts' => $products->pluck('discount', 'id')->toArray(),
            'ratings' => $products->pluck('positive_feedback', 'id')->toArray(),
            'sales' => $products->pluck('sales_180day', 'id')->toArray(),
        ];
    }
}
