<?php

namespace App\Console\Commands;

use App\Models\Deal;
use App\Services\ShopifyService;
use Illuminate\Console\Command;

class RestoreExpiredDeals extends Command
{
    protected $signature = 'deals:restore-expired';
    protected $description = 'Restore original prices in Shopify for deals that have passed their end time';

    public function handle(ShopifyService $shopify): int
    {
        $deals = Deal::where('restored', false)
            ->whereNotNull('ends_at')
            ->where('ends_at', '<=', now())
            ->with('dealProducts')
            ->get();

        foreach ($deals as $deal) {
            foreach ($deal->dealProducts as $dp) {
                if ($dp->restored) {
                    continue;
                }
                try {
                    $shopify->updateVariantPrice(
                        $dp->shopify_variant_id,
                        (string) $dp->original_price,
                        $dp->original_compare_at_price !== null ? (string) $dp->original_compare_at_price : null
                    );
                    $dp->update(['restored' => true]);
                } catch (\Throwable $e) {
                    $this->warn("DealProduct {$dp->id}: " . $e->getMessage());
                }
            }
            $deal->update(['restored' => true]);
        }

        $this->info('Restored ' . $deals->count() . ' deal(s).');
        return self::SUCCESS;
    }
}
