<?php

declare(strict_types=1);

namespace App\Services\AiAssistant\Tools;

use App\Services\AiAssistant\AiComponentRenderer;
use App\Services\AiAssistant\StructuredResponse;
use App\Services\DealFinderService;

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

    public function find(string $type = 'best', ?int $categoryId = null, ?int $limit = 10): StructuredResponse
    {
        $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 StructuredResponse::fromText(
                '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((float) $savings['original_price'], 2).'~~ **$'.number_format((float) $savings['discounted_price'], 2).'** (Save $'.number_format((float) $savings['discount_amount'], 2)." / {$savings['discount_percentage']}%)\n";
            }

            if ($savings['has_promo_code']) {
                $response .= "  - Promo Code: **{$savings['promo_code']}** (Save additional $".number_format((float) $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((float) $maxSavings, 2)." with discounts and promo codes!\n";

        // Generate HTML with deal cards
        $dealCards = '';
        foreach ($products as $product) {
            $dealCards .= $this->renderer->dealCard($product, $type);
        }

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

        return StructuredResponse::withHtml($response, $html, [
            'deal_type' => $type,
            'count' => $products->count(),
            'max_savings' => $maxSavings,
        ]);
    }
}
