<?php

declare(strict_types=1);

namespace App\Services\AiAssistant\Tools;

use App\Models\Product;
use App\Services\AiAssistant\AiComponentRenderer;
use App\Services\AiAssistant\StructuredResponse;

class ShoppingHelperTools
{
    public function __construct(
        protected AiComponentRenderer $renderer
    ) {}

    public function findByPriceRange(float $min, float $max, ?int $categoryId = null, ?int $limit = 10): StructuredResponse
    {
        $limit = min($limit ?? 10, 50);

        $products = Product::query()
            ->when($categoryId, fn ($q) => $q->where('category_id', $categoryId))
            ->whereRaw('COALESCE(discount_price, price) BETWEEN ? AND ?', [$min, $max])
            ->with('category')
            ->orderByRaw('COALESCE(discount_price, price)')
            ->limit($limit)
            ->get();

        if ($products->isEmpty()) {
            return StructuredResponse::fromText(
                "No products found in the price range \${$min} - \${$max}. Try expanding your budget."
            );
        }

        $text = "Found {$products->count()} product(s) between \${$min} and \${$max}:\n\n";

        foreach ($products as $product) {
            $effectivePrice = $product->discount_price ?? $product->price;
            $text .= "- **{$product->name_en}** (ID: {$product->id}) - \${$effectivePrice}";

            if ($product->discount_price) {
                $text .= " (~~\${$product->price}~~, {$product->discount}% off)";
            }

            $text .= "\n";
        }

        $html = $this->renderer->productGrid(
            $products,
            "Products between \${$min} - \${$max}"
        );

        return StructuredResponse::withHtml($text, $html, [
            'price_range' => ['min' => $min, 'max' => $max],
            'count' => $products->count(),
        ]);
    }

    public function getBestSellers(?int $categoryId = null, ?int $limit = 10): StructuredResponse
    {
        $limit = min($limit ?? 10, 50);

        $products = Product::query()
            ->when($categoryId, fn ($q) => $q->where('category_id', $categoryId))
            ->with('category')
            ->orderBy('sales_180day', 'desc')
            ->limit($limit)
            ->get();

        if ($products->isEmpty()) {
            return StructuredResponse::fromText(
                'No best sellers found at the moment.'
            );
        }

        $text = "**Top {$products->count()} Best Sellers**\n\n";

        foreach ($products as $index => $product) {
            $text .= ($index + 1).". **{$product->name_en}** (ID: {$product->id})\n";
            $text .= "   - Sales: {$product->sales_180day} | Price: \${$product->price}\n";
        }

        $html = $this->renderer->productGrid(
            $products,
            'Best Sellers',
            '🏆 Top'
        );

        return StructuredResponse::withHtml($text, $html, [
            'count' => $products->count(),
            'category_id' => $categoryId,
        ]);
    }

    public function getUrgentDeals(?int $limit = 10): StructuredResponse
    {
        $limit = min($limit ?? 10, 50);

        // Find products with high discount percentage
        $products = Product::query()
            ->whereNotNull('discount_price')
            ->whereColumn('discount_price', '<', 'price')
            ->with('category')
            ->orderByRaw('(price - discount_price) / price DESC')
            ->limit($limit)
            ->get();

        if ($products->isEmpty()) {
            return StructuredResponse::fromText(
                'No urgent deals available at the moment. Check back soon!'
            );
        }

        $text = "**🔥 Urgent Deals - Save Big!**\n\n";

        foreach ($products as $product) {
            $savings = $product->price - $product->discount_price;
            $text .= "- **{$product->name_en}** (ID: {$product->id})\n";
            $text .= "   - ~~\${$product->price}~~ \${$product->discount_price} (Save \${$savings} / {$product->discount}% off)\n";
        }

        $dealCards = '';
        foreach ($products as $product) {
            $dealCards .= $this->renderer->dealCard($product, 'flash');
        }

        $html = '<div class="space-y-3 mt-4">'.$dealCards.'</div>';

        return StructuredResponse::withHtml($text, $html, [
            'count' => $products->count(),
            'max_discount' => $products->first()?->discount ?? 0,
        ]);
    }

    public function getLowStock(?int $categoryId = null, ?int $limit = 10): StructuredResponse
    {
        $limit = min($limit ?? 10, 50);

        // Find products with limited coupon quantity
        $products = Product::query()
            ->whereNotNull('code_quantity')
            ->where('code_quantity', '>', 0)
            ->where('code_end_time', '>', now())
            ->when($categoryId, fn ($q) => $q->where('category_id', $categoryId))
            ->with('category')
            ->orderBy('code_quantity', 'asc')
            ->limit($limit)
            ->get();

        if ($products->isEmpty()) {
            return StructuredResponse::fromText(
                'No limited quantity offers available right now.'
            );
        }

        $text = "**⚡ Limited Time Offers - Act Fast!**\n\n";

        foreach ($products as $product) {
            $text .= "- **{$product->name_en}** (ID: {$product->id})\n";
            $text .= "   - Only {$product->code_quantity} codes left!\n";
            if ($product->code_end_time) {
                $text .= "   - Expires: {$product->code_end_time->format('M d, Y')}\n";
            }
            $text .= "\n";
        }

        $dealCards = '';
        foreach ($products as $product) {
            $dealCards .= $this->renderer->dealCard($product, 'flash');
        }

        $html = '<div class="space-y-3 mt-4">'.$dealCards.'</div>';

        return StructuredResponse::withHtml($text, $html, [
            'count' => $products->count(),
        ]);
    }
}
