<?php

declare(strict_types=1);

namespace Tests\Feature\Account;

use Mtc\MercuryDataModels\Customer;

class LoginTest extends AccountTestCase
{
    public function testLogsInWithValidCredentials(): void
    {
        Customer::create([
            'first_name' => 'Grace',
            'last_name' => 'Hopper',
            'email' => 'grace@example.com',
            'password' => 'nanoseconds',
        ]);

        $response = $this->asTenant(tenant())->postJson(route('account.login'), [
            'email' => 'grace@example.com',
            'password' => 'nanoseconds',
        ]);

        $response->assertStatus(200);
        $response->assertJsonPath('customer.email', 'grace@example.com');
        $this->assertAuthenticated('customer');
    }

    public function testRejectsWrongPassword(): void
    {
        Customer::create([
            'first_name' => 'Grace',
            'last_name' => 'Hopper',
            'email' => 'grace@example.com',
            'password' => 'nanoseconds',
        ]);

        $response = $this->asTenant(tenant())->postJson(route('account.login'), [
            'email' => 'grace@example.com',
            'password' => 'wrong',
        ]);

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

    public function testRejectsUnknownEmail(): void
    {
        $response = $this->asTenant(tenant())->postJson(route('account.login'), [
            'email' => 'ghost@example.com',
            'password' => 'whatever',
        ]);

        $response->assertStatus(422);
        $this->assertGuest('customer');
    }

    public function testLogsOut(): void
    {
        $customer = Customer::create([
            'first_name' => 'Grace',
            'last_name' => 'Hopper',
            'email' => 'grace@example.com',
            'password' => 'nanoseconds',
        ]);

        $response = $this->asTenant(tenant())
            ->actingAs($customer, 'customer')
            ->deleteJson(route('account.logout'));

        $response->assertStatus(204);
        $this->assertGuest('customer');
    }
}
