<?php

namespace Tests\Feature\Auth;

use App\Models\Package;
use App\Models\Tenant;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Str;
use Tests\TestCase;

class RegistrationTest extends TestCase
{
    use RefreshDatabase;

    private function assertRedirectsToVerification($response): void
    {
        $expected = route('verification.notice', absolute: false);
        $target = $response->headers->get('Location')
            ?? $response->headers->get('X-Inertia-Location');

        $this->assertNotNull($target, 'Registration response did not include a redirect target.');

        $this->assertTrue(
            $target === $expected || Str::endsWith($target, $expected),
            'Registration should redirect or instruct Inertia to navigate to the verification notice.'
        );
    }

    public function test_registration_screen_can_be_rendered(): void
    {
        $response = $this->get(route('register'));

        $response->assertStatus(200);
    }

    public function test_new_users_can_register(): void
    {
        $response = $this->post(route('register.store'), [
            'name' => 'Test User',
            'username' => 'testuser',
            'email' => 'test@example.com',
            'password' => 'Password123!',
            'password_confirmation' => 'Password123!',
            'first_name' => 'Max',
            'last_name' => 'Mustermann',
            'address' => 'Musterstr. 1',
            'phone' => '+49123456789',
            'privacy_consent' => true,
        ]);

        $this->assertAuthenticated();
        $this->assertRedirectsToVerification($response);
        $this->assertDatabaseHas('users', ['email' => 'test@example.com']);
        $this->assertDatabaseHas('tenants', [
            'user_id' => User::latest()->first()->id,
        ]);
    }

    public function test_registration_with_free_package_assigns_tenant_package(): void
    {
        $freePackage = Package::factory()->endcustomer()->create(['price' => 0]);

        $response = $this->post(route('register.store'), [
            'name' => 'Test User',
            'username' => 'testuserfree',
            'email' => 'free@example.com',
            'password' => 'Password123!',
            'password_confirmation' => 'Password123!',
            'first_name' => 'Max',
            'last_name' => 'Mustermann',
            'address' => 'Musterstr. 1',
            'phone' => '+49123456789',
            'privacy_consent' => true,
            'package_id' => $freePackage->id,
        ]);

        $this->assertAuthenticated();
        $this->assertRedirectsToVerification($response);

        $user = User::latest()->first();
        $tenant = Tenant::where('user_id', $user->id)->first();

        $this->assertDatabaseHas('tenant_packages', [
            'tenant_id' => $tenant->id,
            'package_id' => $freePackage->id,
            'active' => true,
            'price' => 0,
        ]);

        $this->assertDatabaseHas('package_purchases', [
            'tenant_id' => $tenant->id,
            'package_id' => $freePackage->id,
            'type' => 'endcustomer_event',
            'price' => 0,
        ]);

        $this->assertEquals('active', $tenant->subscription_status);
    }

    public function test_registration_with_paid_package_redirects_to_buy(): void
    {
        $paidPackage = Package::factory()->endcustomer()->create(['price' => 10]);

        $response = $this->post(route('register.store'), [
            'name' => 'Test User',
            'username' => 'testuserpaid',
            'email' => 'paid@example.com',
            'password' => 'Password123!',
            'password_confirmation' => 'Password123!',
            'first_name' => 'Max',
            'last_name' => 'Mustermann',
            'address' => 'Musterstr. 1',
            'phone' => '+49123456789',
            'privacy_consent' => true,
            'package_id' => $paidPackage->id,
        ]);

        $response->assertRedirect(route('buy.packages', [
            'locale' => 'de',
            'packageId' => $paidPackage->id,
        ]));
        $this->assertDatabaseHas('users', ['email' => 'paid@example.com']);
        $this->assertDatabaseMissing('tenant_packages', ['package_id' => $paidPackage->id]);
    }

    public function test_registration_fails_with_invalid_email(): void
    {
        $response = $this->post(route('register.store'), [
            'name' => 'Test User',
            'username' => 'invaliduser',
            'email' => 'invalid-email',
            'password' => 'password',
            'password_confirmation' => 'password',
            'first_name' => 'Max',
            'last_name' => 'Mustermann',
            'address' => 'Musterstr. 1',
            'phone' => '+49123456789',
            'privacy_consent' => true,
        ]);

        $response->assertStatus(302);
        $response->assertSessionHasErrors(['email']);
        $this->assertDatabaseMissing('users', ['email' => 'invalid-email']);
    }

    public function test_registration_success_sets_status_flash(): void
    {
        $response = $this->post(route('register.store'), [
            'name' => 'Test User',
            'username' => 'successreg',
            'email' => 'successreg@example.com',
            'password' => 'Password123!',
            'password_confirmation' => 'Password123!',
            'first_name' => 'Max',
            'last_name' => 'Mustermann',
            'address' => 'Musterstr. 1',
            'phone' => '+49123456789',
            'privacy_consent' => true,
        ]);

        $this->assertAuthenticated();
        $this->assertRedirectsToVerification($response);
    }

    public function test_registration_fails_with_short_password(): void
    {
        $response = $this->post(route('register.store'), [
            'name' => 'Test User',
            'username' => 'shortpass',
            'email' => 'short@example.com',
            'password' => 'short',
            'password_confirmation' => 'short',
            'first_name' => 'Max',
            'last_name' => 'Mustermann',
            'address' => 'Musterstr. 1',
            'phone' => '+49123456789',
            'privacy_consent' => true,
        ]);

        $response->assertStatus(302);
        $response->assertSessionHasErrors(['password']);
        $this->assertDatabaseMissing('users', ['email' => 'short@example.com']);
    }

    public function test_registration_fails_without_privacy_consent(): void
    {
        $response = $this->post(route('register.store'), [
            'name' => 'Test User',
            'username' => 'noconsent',
            'email' => 'noconsent@example.com',
            'password' => 'Password123!',
            'password_confirmation' => 'Password123!',
            'first_name' => 'Max',
            'last_name' => 'Mustermann',
            'address' => 'Musterstr. 1',
            'phone' => '+49123456789',
            'privacy_consent' => false,
        ]);

        $response->assertStatus(302);
        $response->assertSessionHasErrors(['privacy_consent']);
        $this->assertDatabaseMissing('users', ['email' => 'noconsent@example.com']);
    }

    public function test_registration_fails_with_duplicate_email(): void
    {
        User::factory()->create(['email' => 'duplicate@example.com']);

        $response = $this->post(route('register.store'), [
            'name' => 'Duplicate User',
            'username' => 'duplicate',
            'email' => 'duplicate@example.com',
            'password' => 'Password123!',
            'password_confirmation' => 'Password123!',
            'first_name' => 'Max',
            'last_name' => 'Mustermann',
            'address' => 'Musterstr. 1',
            'phone' => '+49123456789',
            'privacy_consent' => true,
        ]);

        $response->assertStatus(302);
        $response->assertSessionHasErrors(['email']);
    }

    public function test_registration_fails_with_mismatched_passwords(): void
    {
        $response = $this->post(route('register.store'), [
            'name' => 'Test User',
            'username' => 'mismatch',
            'email' => 'mismatch@example.com',
            'password' => 'Password123!',
            'password_confirmation' => 'different123!',
            'first_name' => 'Max',
            'last_name' => 'Mustermann',
            'address' => 'Musterstr. 1',
            'phone' => '+49123456789',
            'privacy_consent' => true,
        ]);

        $response->assertStatus(302);
        $response->assertSessionHasErrors(['password']);
        $this->assertDatabaseMissing('users', ['email' => 'mismatch@example.com']);
    }

    public function test_registration_with_invalid_package_id_triggers_validation_error(): void
    {
        $response = $this->post(route('register.store'), [
            'name' => 'Test User',
            'username' => 'invalidpkg',
            'email' => 'invalidpkg@example.com',
            'password' => 'Password123!',
            'password_confirmation' => 'Password123!',
            'first_name' => 'Max',
            'last_name' => 'Mustermann',
            'address' => 'Musterstr. 1',
            'phone' => '+49123456789',
            'privacy_consent' => true,
            'package_id' => 999,
        ]);

        $response->assertStatus(302);
        $response->assertSessionHasErrors(['package_id']);
        $this->assertDatabaseMissing('users', ['email' => 'invalidpkg@example.com']);
    }
}
