<?php

namespace App\Console\Commands;

use App\Contracts\ListingScraper;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;

#[Signature('scraping:listing {url : The product listing page URL to scrape}')]
#[Description('Scrape product candidates from a listing page using Puppeteer')]
class ScrapeListingCommand extends Command
{
    public function handle(ListingScraper $scraper): int
    {
        $url = (string) $this->argument('url');
        $result = $scraper->scrape($url);

        if (! $result->succeeded()) {
            $this->components->error($result->error ?? 'Listing scrape failed.');

            return self::FAILURE;
        }

        $this->components->info(sprintf(
            'Scraped %d product candidate(s) from %s%s',
            count($result->products),
            $result->url,
            filled($result->browserEngine)
                ? sprintf(' using %s', $result->browserEngine)
                : '',
        ));

        foreach ($result->products as $index => $product) {
            $this->line(sprintf(
                '%d. %s (%s)',
                $index + 1,
                $product->name,
                $product->url,
            ));

            $details = array_filter([
                $product->price ? "price={$product->price}" : null,
                $product->rating ? "rating={$product->rating}" : null,
                $product->reviewCount ? "reviews={$product->reviewCount}" : null,
            ]);

            if ($details !== []) {
                $this->line('   '.implode(' | ', $details));
            }
        }

        if ($result->products === []) {
            $this->components->warn('No products were extracted. The page may be JS-only, blocked, or use unfamiliar URL patterns.');
        }

        return self::SUCCESS;
    }
}
