<?php

declare(strict_types=1);

use App\Models\User;
use Database\Seeders\RoleAndPermissionSeeder;

beforeEach(function (): void {
    $this->seed(RoleAndPermissionSeeder::class);
    $this->accountUrl = 'http://'.config('app.domains.account');
});

it('renders the registration page', function (): void {
    $this->get($this->accountUrl.'/register')
        ->assertOk();
});

it('registers a new user', function (): void {
    $this->post($this->accountUrl.'/register', [
        'name' => 'Test User',
        'email' => 'test@example.com',
        'password' => 'password123!',
        'password_confirmation' => 'password123!',
    ])->assertRedirect();

    $this->assertDatabaseHas('users', [
        'email' => 'test@example.com',
    ]);
});

it('assigns customer role on registration', function (): void {
    $this->post($this->accountUrl.'/register', [
        'name' => 'Test User',
        'email' => 'test@example.com',
        'password' => 'password123!',
        'password_confirmation' => 'password123!',
    ]);

    $user = User::where('email', 'test@example.com')->first();
    expect($user->hasRole('customer'))->toBeTrue();
});

it('creates user profile on registration', function (): void {
    $this->post($this->accountUrl.'/register', [
        'name' => 'Test User',
        'email' => 'test@example.com',
        'password' => 'password123!',
        'password_confirmation' => 'password123!',
    ]);

    $user = User::where('email', 'test@example.com')->first();
    expect($user->profile)->not->toBeNull();
});

it('validates registration input', function (): void {
    $this->post($this->accountUrl.'/register', [
        'name' => '',
        'email' => 'not-an-email',
        'password' => 'short',
        'password_confirmation' => 'mismatch',
    ])->assertSessionHasErrors(['name', 'email', 'password']);
});

it('prevents duplicate email registration', function (): void {
    User::factory()->create(['email' => 'taken@example.com']);

    $this->post($this->accountUrl.'/register', [
        'name' => 'Test User',
        'email' => 'taken@example.com',
        'password' => 'password123!',
        'password_confirmation' => 'password123!',
    ])->assertSessionHasErrors('email');
});
