<?php

namespace Tests\Feature\Auth;

use App\Models\Cart;
use App\Models\Product;
use App\Models\ProductVariant;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class CustomerAuthenticationTest extends TestCase
{
    use RefreshDatabase;

    public function test_customer_can_register_and_is_logged_in(): void
    {
        $response = $this->post('/register', [
            'name' => 'Ayesha Khan',
            'email' => 'ayesha@example.com',
            'phone' => '03001234567',
            'password' => 'password123',
            'password_confirmation' => 'password123',
        ]);

        $response->assertRedirect(route('home'));
        $this->assertAuthenticated();
        $this->assertDatabaseHas('users', ['email' => 'ayesha@example.com', 'role' => 'customer']);
    }

    public function test_customer_can_login_with_correct_credentials(): void
    {
        $user = $this->customer(['password' => 'password123']);

        $response = $this->post('/login', ['email' => $user->email, 'password' => 'password123']);

        $response->assertRedirect(route('home'));
        $this->assertAuthenticatedAs($user);
    }

    public function test_customer_cannot_login_with_wrong_password(): void
    {
        $user = $this->customer(['password' => 'password123']);

        $response = $this->post('/login', ['email' => $user->email, 'password' => 'wrong-password']);

        $response->assertSessionHasErrors('email');
        $this->assertGuest();
    }

    public function test_authenticated_customer_can_logout(): void
    {
        $user = $this->customer();

        $response = $this->actingAs($user)->post('/logout');

        $response->assertRedirect(route('home'));
        $this->assertGuest();
    }

    public function test_guest_cart_merges_into_user_cart_on_login(): void
    {
        $category = \App\Models\Category::factory()->create();
        $product = Product::factory()->for($category)->create();
        $variant = ProductVariant::factory()->for($product)->withStock(10)->create();

        $this->post('/cart/add/'.$product->slug, ['variant_id' => $variant->id, 'quantity' => 2]);
        $guestCart = Cart::whereNull('user_id')->first();
        $this->assertNotNull($guestCart);

        $user = $this->customer(['password' => 'password123']);
        event(new \Illuminate\Auth\Events\Login('web', $user, false));

        $this->assertDatabaseMissing('carts', ['id' => $guestCart->id]);
        $userCart = Cart::where('user_id', $user->id)->first();
        $this->assertSame(2, $userCart->items()->sum('quantity'));
    }
}
