<?php

namespace App\Services;

use App\Models\Product;

class ProductQAService
{
    public function answerQuestion(int $productId, string $question): array
    {
        $product = Product::with('category')->findOrFail($productId);

        return [
            'product' => [
                'id' => $product->id,
                'name' => $product->name_en ?? $product->name_ar,
                'description' => $this->getLocalizedDescription($product),
                'price' => $product->price,
                'discount' => $product->discount,
                'category' => $product->category?->name_en ?? $product->category?->name_ar,
            ],
            'answer' => $this->generateAnswer($product, $question),
            'specifications' => $this->extractSpecs($product),
        ];
    }

    public function extractSpecs(Product $product): array
    {
        return [
            'pricing' => [
                'original_price' => (float) $product->price,
                'discount_price' => $product->discount_price ? (float) $product->discount_price : null,
                'discount_percentage' => $product->discount ? (float) $product->discount : 0,
                'currency' => $product->currency,
            ],
            'performance' => [
                'sales_count' => $product->sales_180day ?? 0,
                'rating' => $product->positive_feedback ?? 0,
                'clicks' => $product->clicks ?? 0,
            ],
            'promotions' => [
                'has_promo_code' => ! empty($product->code_name),
                'promo_code' => $product->code_name,
                'promo_value' => $product->code_value,
                'promo_valid_until' => $product->code_end_time?->format('Y-m-d'),
            ],
            'commission' => [
                'direct_rate' => $product->direct_commission_rate,
                'indirect_rate' => $product->indirect_commission_rate,
            ],
        ];
    }

    public function compareFeatures(array $productIds, string $feature): array
    {
        $products = Product::with('category')
            ->whereIn('id', $productIds)
            ->get()
            ->keyBy('id');

        $comparison = [];

        foreach ($productIds as $id) {
            if (! isset($products[$id])) {
                continue;
            }

            $product = $products[$id];
            $comparison[$id] = $this->getFeatureValue($product, $feature);
        }

        return [
            'feature' => $feature,
            'comparison' => $comparison,
            'best' => $this->getBestForFeature($products, $feature),
        ];
    }

    protected function generateAnswer(Product $product, string $question): string
    {
        $question = strtolower($question);

        if (str_contains($question, 'price') || str_contains($question, 'cost')) {
            return $this->answerPriceQuestion($product);
        }

        if (str_contains($question, 'discount') || str_contains($question, 'deal') || str_contains($question, 'offer')) {
            return $this->answerDiscountQuestion($product);
        }

        if (str_contains($question, 'rating') || str_contains($question, 'review') || str_contains($question, 'quality')) {
            return $this->answerRatingQuestion($product);
        }

        if (str_contains($question, 'popular') || str_contains($question, 'sales')) {
            return $this->answerPopularityQuestion($product);
        }

        return $this->getLocalizedDescription($product);
    }

    protected function answerPriceQuestion(Product $product): string
    {
        $price = number_format($product->price, 2);
        $currency = $product->currency ?? 'USD';

        if ($product->discount_price) {
            $discountPrice = number_format($product->discount_price, 2);

            return "The original price is {$price} {$currency}, but with discount it's available for {$discountPrice} {$currency}.";
        }

        return "The current price is {$price} {$currency}.";
    }

    protected function answerDiscountQuestion(Product $product): string
    {
        if ($product->discount > 0) {
            $discount = number_format($product->discount, 2);
            $response = "Yes! This product has a {$discount}% discount.";

            if ($product->code_name) {
                $response .= " Plus, there's a promo code '{$product->code_name}' that saves you {$product->code_value}.";
            }

            return $response;
        }

        return "This product doesn't currently have a discount.";
    }

    protected function answerRatingQuestion(Product $product): string
    {
        $rating = number_format($product->positive_feedback ?? 0, 1);
        $sales = $product->sales_180day ?? 0;

        return "This product has a rating of {$rating}/100 based on customer feedback, with {$sales} sales in the last 180 days.";
    }

    protected function answerPopularityQuestion(Product $product): string
    {
        $sales = $product->sales_180day ?? 0;
        $clicks = $product->clicks ?? 0;

        return "This product has {$sales} sales and {$clicks} views in the last 180 days, making it quite popular.";
    }

    protected function getLocalizedDescription(Product $product): string
    {
        return $product->description_en ?? $product->description_ar ?? 'No description available.';
    }

    protected function getFeatureValue(Product $product, string $feature): mixed
    {
        return match ($feature) {
            'price' => $product->price,
            'discount' => $product->discount,
            'rating' => $product->positive_feedback,
            'sales' => $product->sales_180day,
            'category' => $product->category?->name_en ?? $product->category?->name_ar,
            default => null,
        };
    }

    protected function getBestForFeature($products, string $feature): ?int
    {
        return match ($feature) {
            'price' => $products->sortBy('price')->first()?->id,
            'discount', 'rating', 'sales' => $products->sortByDesc($feature)->first()?->id,
            default => null,
        };
    }
}
