<?php

declare(strict_types=1);

namespace App\Console\Commands;

use App\Models\Plan;
use Illuminate\Console\Command;
use Stripe\Price;
use Stripe\Product;
use Stripe\Stripe;

class SyncStripePrices extends Command
{
    protected $signature = 'stripe:sync-prices {--force : Force recreate all prices}';

    protected $description = 'Sync plans with Stripe prices';

    public function handle(): int
    {
        Stripe::setApiKey(config('cashier.secret'));

        $plans = Plan::all();

        $this->info("Syncing {$plans->count()} plans with Stripe...");

        $progressBar = $this->output->createProgressBar($plans->count());
        $progressBar->start();

        foreach ($plans as $plan) {
            try {
                // Create or get Stripe product
                $product = Product::create([
                    'name' => $plan->name,
                    'description' => "EZSCALE {$plan->service_type} - {$plan->name}",
                    'metadata' => [
                        'plan_id' => $plan->id,
                        'plan_slug' => $plan->slug,
                    ],
                ]);

                // Create Stripe price
                $interval = match ($plan->billing_cycle) {
                    'monthly' => 'month',
                    'quarterly' => 'month',
                    'semi_annually' => 'month',
                    'annually' => 'year',
                    default => 'month',
                };

                $intervalCount = match ($plan->billing_cycle) {
                    'monthly' => 1,
                    'quarterly' => 3,
                    'semi_annually' => 6,
                    'annually' => 1,
                    default => 1,
                };

                $price = Price::create([
                    'product' => $product->id,
                    'currency' => 'usd',
                    'unit_amount' => (int) ($plan->price * 100), // Convert to cents
                    'recurring' => [
                        'interval' => $interval,
                        'interval_count' => $intervalCount,
                    ],
                    'metadata' => [
                        'plan_id' => $plan->id,
                        'plan_slug' => $plan->slug,
                    ],
                ]);

                // Update plan with Stripe price ID
                $plan->update([
                    'stripe_price_id' => $price->id,
                    'stripe_product_id' => $product->id,
                ]);

                $progressBar->advance();
            } catch (\Exception $e) {
                $this->newLine();
                $this->error("Failed to sync {$plan->name}: {$e->getMessage()}");
                $progressBar->advance();
            }
        }

        $progressBar->finish();
        $this->newLine(2);
        $this->info('✓ Stripe prices synced successfully!');

        return self::SUCCESS;
    }
}
