<?php

declare(strict_types=1);

namespace Tests\Feature\Account;

use Mtc\MercuryDataModels\Customer;

class RegisterTest extends AccountTestCase
{
    public function testRegistersNewCustomerAndLogsIn(): void
    {
        $response = $this->asTenant(tenant())->postJson(route('account.register'), [
            'first_name' => 'Ada',
            'last_name' => 'Lovelace',
            'email' => 'ada@example.com',
            'password' => 'correct-horse-battery',
            'password_confirmation' => 'correct-horse-battery',
        ]);

        $response->assertStatus(201);
        $response->assertJsonPath('customer.email', 'ada@example.com');

        $customer = Customer::query()->where('email', 'ada@example.com')->firstOrFail();
        $this->assertNotEmpty($customer->password);

        $this->assertAuthenticatedAs($customer, 'customer');
    }

    public function testUpgradesExistingAnonymousCustomer(): void
    {
        Customer::create([
            'first_name' => 'Existing',
            'last_name' => 'User',
            'email' => 'existing@example.com',
        ]);

        $response = $this->asTenant(tenant())->postJson(route('account.register'), [
            'first_name' => 'Existing',
            'last_name' => 'User',
            'email' => 'existing@example.com',
            'password' => 'new-password-1',
            'password_confirmation' => 'new-password-1',
        ]);

        $response->assertStatus(201);

        $this->assertSame(
            1,
            Customer::query()->where('email', 'existing@example.com')->count()
        );

        $customer = Customer::query()->where('email', 'existing@example.com')->firstOrFail();
        $this->assertNotEmpty($customer->password);
    }

    public function testRejectsRegistrationWhenEmailAlreadyHasPassword(): void
    {
        Customer::create([
            'first_name' => 'Has',
            'last_name' => 'Account',
            'email' => 'taken@example.com',
            'password' => 'existing-password',
        ]);

        $response = $this->asTenant(tenant())->postJson(route('account.register'), [
            'first_name' => 'Has',
            'last_name' => 'Account',
            'email' => 'taken@example.com',
            'password' => 'another-password-1',
            'password_confirmation' => 'another-password-1',
        ]);

        $response->assertStatus(422);
        $response->assertJsonValidationErrors(['email']);
    }
}
