<?php

namespace Tests\Feature;

use App\Models\Contact;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ContactTest extends TestCase
{
    use RefreshDatabase;

    public function test_contacts_are_scoped_to_users(): void
    {
        // 1. Create two distinct users
        $user1 = User::factory()->create();
        $user2 = User::factory()->create();

        // 2. Authenticate User 1 and create a contact
        $this->actingAs($user1);
        $response = $this->post('/contacts', [
            'first_name' => 'MD',
            'last_name' => 'Kaber',
            'email' => 'rafkabir05.rk@gmail.com',
            'status' => 'subscribed',
        ]);
        $response->assertRedirect('/contacts');
        $this->assertDatabaseHas('contacts', [
            'user_id' => $user1->id,
            'email' => 'rafkabir05.rk@gmail.com',
        ]);

        // 3. Authenticate User 2 and create a contact with the SAME email
        $this->actingAs($user2);
        $response2 = $this->post('/contacts', [
            'first_name' => 'MD',
            'last_name' => 'Kaber',
            'email' => 'rafkabir05.rk@gmail.com',
            'status' => 'subscribed',
        ]);
        $response2->assertRedirect('/contacts');
        $this->assertDatabaseHas('contacts', [
            'user_id' => $user2->id,
            'email' => 'rafkabir05.rk@gmail.com',
        ]);

        // 4. Verify User 2 cannot see User 1's contacts
        $this->actingAs($user2);
        $contactsUser2 = Contact::all();
        $this->assertCount(1, $contactsUser2);
        $this->assertEquals($user2->id, $contactsUser2->first()->user_id);

        // 5. Verify User 1 cannot create a second contact with the same email
        $this->actingAs($user1);
        $response3 = $this->post('/contacts', [
            'first_name' => 'MD Rafi',
            'last_name' => 'Kabir',
            'email' => 'rafkabir05.rk@gmail.com',
            'status' => 'subscribed',
        ]);
        $response3->assertSessionHasErrors('email');
    }
}
