<?php

namespace Tests\Feature;

use App\Models\Package;
use App\Models\User;
use App\Support\CheckoutRoutes;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Socialite\Contracts\Factory as SocialiteFactory;
use Laravel\Socialite\Contracts\Provider as SocialiteProvider;
use Laravel\Socialite\Contracts\User as SocialiteUserContract;
use Mockery;
use Tests\TestCase;

class CheckoutGoogleControllerTest extends TestCase
{
    use RefreshDatabase;

    protected function tearDown(): void
    {
        Mockery::close();
        parent::tearDown();
    }

    public function test_redirect_persists_package_context_and_delegates_to_google(): void
    {
        $package = Package::factory()->create();

        $provider = Mockery::mock(SocialiteProvider::class);
        $provider->shouldReceive('scopes')->andReturnSelf();
        $provider->shouldReceive('with')->andReturnSelf();
        $provider->shouldReceive('redirect')->once()->andReturn(redirect('/google/auth'));

        $this->mock(SocialiteFactory::class, function ($mock) use ($provider) {
            $mock->shouldReceive('driver')->with('google')->andReturn($provider);
        });

        $response = $this->get('/checkout/auth/google?package_id='.$package->id.'&locale=de');

        $response->assertRedirect('/google/auth');
        $this->assertSame($package->id, session('checkout_google_payload.package_id'));
    }

    public function test_callback_logs_in_existing_user_and_attaches_tenant(): void
    {
        $package = Package::factory()->create(['price' => 0]);
        $existingUser = User::factory()->create([
            'email' => 'checkout-google@example.com',
            'pending_purchase' => false,
        ]);

        $googleUser = Mockery::mock(SocialiteUserContract::class);
        $googleUser->shouldReceive('getEmail')->andReturn('checkout-google@example.com');
        $googleUser->shouldReceive('getName')->andReturn('Checkout Google');
        $googleUser->shouldReceive('getAvatar')->andReturn(null);
        $googleUser->shouldReceive('getRaw')->andReturn([]);

        $provider = Mockery::mock(SocialiteProvider::class);
        $provider->shouldReceive('user')->andReturn($googleUser);

        $this->mock(SocialiteFactory::class, function ($mock) use ($provider) {
            $mock->shouldReceive('driver')->with('google')->andReturn($provider);
        });

        $response = $this
            ->withSession([
                'checkout_google_payload' => ['package_id' => $package->id, 'locale' => 'de'],
            ])
            ->get('/checkout/auth/google/callback');

        $response->assertRedirect(CheckoutRoutes::wizardUrl($package->id, 'de'));

        $this->assertAuthenticatedAs($existingUser);

        $user = auth()->user();
        $this->assertSame('checkout-google@example.com', $user->email);
        $this->assertTrue($user->pending_purchase);
        $this->assertNotNull($user->tenant);
        $this->assertDatabaseHas('tenant_packages', [
            'tenant_id' => $user->tenant_id,
            'package_id' => $package->id,
        ]);
    }

    public function test_callback_with_missing_email_flashes_error(): void
    {
        $package = Package::factory()->create();

        $googleUser = Mockery::mock(SocialiteUserContract::class);
        $googleUser->shouldReceive('getEmail')->andReturn(null);
        $googleUser->shouldReceive('getName')->andReturn('No Email');
        $googleUser->shouldReceive('getAvatar')->andReturn(null);
        $googleUser->shouldReceive('getRaw')->andReturn([]);

        $provider = Mockery::mock(SocialiteProvider::class);
        $provider->shouldReceive('user')->andReturn($googleUser);

        $this->mock(SocialiteFactory::class, function ($mock) use ($provider) {
            $mock->shouldReceive('driver')->with('google')->andReturn($provider);
        });

        $response = $this
            ->withSession([
                'checkout_google_payload' => ['package_id' => $package->id, 'locale' => 'en'],
            ])
            ->get('/checkout/auth/google/callback');

        $response->assertRedirect(CheckoutRoutes::wizardUrl($package->id, 'en'));
        $response->assertSessionHas('checkout_google_error');
        $this->assertGuest();
    }
}
