<?php

declare(strict_types=1);

namespace App\Services\AiAssistant\Tools;

use App\Services\DealFinderService;

class DealTools
{
    public function __construct(
        protected DealFinderService $dealService
    ) {}

    public function find(string $type = 'best', ?int $categoryId = null, ?int $limit = 10): string
    {
        $limit = min($limit, 50);

        $products = match ($type) {
            'flash' => $this->dealService->findFlashDeals($limit),
            'coupon' => $this->dealService->findCouponDeals($limit),
            'value' => $this->dealService->findBestValueDeals($limit),
            default => $this->dealService->findBestDeals($categoryId, $limit),
        };

        if ($products->isEmpty()) {
            return 'No deals found at the moment. Check back later for new promotions!';
        }

        $response = "**Found {$products->count()} great deal";

        if ($products->count() > 1) {
            $response .= 's';
        }

        $response .= "**\n\n";

        $maxSavings = 0;
        foreach ($products as $product) {
            $savings = $this->dealService->calculateSavings($product);
            $maxSavings = max($maxSavings, $savings['total_potential_savings']);

            $response .= "- **{$product->name_en}** (ID: {$product->id})\n";

            if ($savings['has_discount']) {
                $response .= '  - ~~$'.number_format($savings['original_price'], 2).'~~ **$'.number_format($savings['discounted_price'], 2).'** (Save $'.number_format($savings['discount_amount'], 2)." / {$savings['discount_percentage']}%)\n";
            }

            if ($savings['has_promo_code']) {
                $response .= "  - Promo Code: **{$savings['promo_code']}** (Save additional $".number_format($savings['promo_value'], 2).")\n";
            }

            $response .= "  - Rating: {$product->positive_feedback}% positive\n";

            if ($product->category) {
                $response .= "  - Category: {$product->category->name_en}\n";
            }

            $response .= "\n";
        }

        $response .= '**Maximum Savings**: Up to $'.number_format($maxSavings, 2)." with discounts and promo codes!\n";

        return $response;
    }
}
