<?php

declare(strict_types=1);

use App\Models\Plan;
use App\Models\User;
use Illuminate\Support\Facades\DB;

it('migrates subscriptions from old plans to new plans', function () {
    $this->seed(\Database\Seeders\PlanSeeder::class);

    $oldPlan = Plan::create([
        'name' => 'VPS Nano',
        'slug' => 'vps-nano',
        'description' => 'Old nano plan',
        'service_type' => 'vps',
        'price' => 3.50,
        'billing_cycle' => 'monthly',
        'features' => [],
        'sort_order' => 99,
    ]);

    $newPlan = Plan::where('slug', 'vps-1')->first();

    if (! $newPlan) {
        $this->markTestSkipped('New plan vps-1 not found.');
    }

    $user = User::factory()->create();

    DB::table('subscriptions')->insert([
        'user_id' => $user->id,
        'type' => 'vps-nano',
        'stripe_id' => 'sub_test_'.uniqid(),
        'stripe_status' => 'active',
        'plan_id' => $oldPlan->id,
        'billing_cycle' => 'monthly',
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    $this->artisan('plans:migrate-vps')
        ->assertSuccessful();

    $subscription = DB::table('subscriptions')->where('user_id', $user->id)->first();
    expect($subscription->plan_id)->toBe($newPlan->id);
});

it('dry run does not modify data', function () {
    $this->seed(\Database\Seeders\PlanSeeder::class);

    $oldPlan = Plan::create([
        'name' => 'VPS Nano',
        'slug' => 'vps-nano',
        'description' => 'Old nano plan',
        'service_type' => 'vps',
        'price' => 3.50,
        'billing_cycle' => 'monthly',
        'features' => [],
        'sort_order' => 99,
    ]);

    $user = User::factory()->create();

    DB::table('subscriptions')->insert([
        'user_id' => $user->id,
        'type' => 'vps-nano',
        'stripe_id' => 'sub_dry_'.uniqid(),
        'stripe_status' => 'active',
        'plan_id' => $oldPlan->id,
        'billing_cycle' => 'monthly',
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    $this->artisan('plans:migrate-vps', ['--dry-run' => true])
        ->assertSuccessful();

    $subscription = DB::table('subscriptions')->where('user_id', $user->id)->first();
    expect($subscription->plan_id)->toBe($oldPlan->id);
});

it('skips when old plan does not exist', function () {
    $this->seed(\Database\Seeders\PlanSeeder::class);

    // No old plans created, so all mappings should be skipped
    $this->artisan('plans:migrate-vps')
        ->assertSuccessful();
});
