<?php

namespace App\Browser\Jobs\EldoradoRobuxPriceSentry;

use App\Browser\BrowserJob;
use App\Browser\JobDebugScreenshot;
use App\Browser\Jobs\InstagramRepost\DescriptionPipeline\InstagramDescriptionPipeline;
use App\Models\InstagramNotification;
use App\Models\InstagramRepost;
use App\Models\Job;
use App\Models\JobArtifact;
use App\Models\JobRun;
use App\Notification\Notifications\JobDebugNotification;
use App\Notification\Notifications\SimpleNotification;
use App\Notification\Providers\AllNotification;
use App\Services\Instagram\NotificationTypeDetector;
use Facebook\WebDriver\WebDriverBy;
use Illuminate\Contracts\Queue\ShouldBeUniqueUntilProcessing;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Laravel\Dusk\Browser;
use App\Services\AIPrompt\OpenAPIPrompt;

class EldoradoRobuxPriceSentryJob extends BrowserJob implements ShouldBeUniqueUntilProcessing
{
    // === CONFIGURATION ===

    public $timeout = 600; // 10 minutes
    private const APPROXIMATIVE_RUNNING_MINUTES = 20;
    private const LINK = "https://www.eldorado.gg/fr/buy-robux/g/70-0-0";
    protected string $downloadFolder = "app/Browser/downloads/EldoradoRobuxPriceSentry/";

    protected Collection $jobInfos;
    protected JobRun $jobRun;

    public function __construct($jobId = 5)
    {
        parent::__construct($jobId);

        $this->downloadFolder = base_path($this->downloadFolder);
    }

    public function run(Browser $browser): ?JobRun
    {
        $startTime = microtime(true);

        Log::info("Running EldoradoRobuxPriceSentryJob");
        $this->jobInfos = Job::find($this->jobId)->jobInfosTable();
        $this->jobRun = new JobRun([
            "job_id" => $this->jobId,
            "success" => false,
        ]);
        $this->jobRun->save();

        dump("visiting " . microtime(true) - $startTime);
        $browser->visit(self::LINK);
        sleep(5);
        $this->sendPrices($browser);

        $this->jobRun->success = true;
        $this->jobRun->save();

        Log::info("EldoradoRobuxPriceSentryJob run ended");

        return $this->jobRun;
    }

    /**
     * @inheritDoc
     */
    public function runTest(Browser $browser): ?JobRun
    {
        $this->jobInfos = Job::find($this->jobId)->jobInfosTable();
        try {
            $browser->visit(self::LINK);
            sleep(5);

            return $this->makeSimpleJobRun(
                true,
                "Test réussi",
                "Datboi a réussi à charger la page Eldorado."
            );
        } catch (\Exception $e) {
            return $this->makeSimpleJobRun(
                false,
                "Test échoué",
                "Datboi n'a pas réussi à charger la page Eldorado :\n" . $e->getMessage()
            );
        }
    }

    private function sendPrices(Browser $browser): void
    {
        $lowestPriceElement = $browser->driver->findElement(WebDriverBy::xpath('(//eld-offer-price)[2]/strong'));
        $lowestPriceText = $lowestPriceElement->getText(); // Ex: " 0,00478 € "
        $lowestPrice = (float)str_replace(["€", ","], ["", "."], trim($lowestPriceText));

        $threshold = floatval(str_replace(",", ".", $this->jobInfos->get("eldorado_robux_price_threshold")));
        dump($threshold);

        Log::info("EldoradoRobuxPriceSentryJob: lowest price = $lowestPrice €, threshold = $threshold €");
        $this->jobRun->addArtifact(new JobArtifact([
            "name" => "Trouvé le prix le plus bas",
            "content" => "- Prix le plus bas : $lowestPrice €/Robux\n- Seuil défini : $threshold €/Robux"
        ]));

        if ($lowestPrice <= $threshold) {
            $message = "Le prix des Robux sur Eldorado est actuellement de **" . number_format($lowestPrice, 5, ",", " ") . " €**/Robux, ce qui est inférieur ou égal au seuil de **" . number_format($threshold, 5, ",", " ") . " €**.\n\n[Voir l'offre sur Eldorado]( " . self::LINK . " )";
            $options = [];

            if ($this->jobInfos->get("eldorado_robux_price_discord_webhook") !== null) { // Custom discord webhook
                $options["discord_webhook_url"] = $this->jobInfos->get("eldorado_robux_price_discord_webhook");
            }

            AllNotification::send(
                new SimpleNotification(
                    $this->jobId,
                    "Alerte Robux Eldorado 🤑",
                    $message
                ),
                $options
            );

            Log::info("EldoradoRobuxPriceSentryJob: alert sent");
        } else {
            Log::info("EldoradoRobuxPriceSentryJob: no alert sent");
        }
    }
}
