<?php

namespace Tests\Unit\Models;

use App\Models\Log;
use App\Models\User;
use Tests\TestCase;

class LogTest extends TestCase
{
    public $user;
    protected function setUp(): void
    {
        parent::setUp();

        $this->user = User::factory()->create();
    }

    /** @test */
    public function it_can_create_a_log_with_factory(): void
    {
        $log = Log::factory()->create();

        $this->assertInstanceOf(Log::class, $log);
        $this->assertIsString($log->email);
        $this->assertIsString($log->ip);
    }

    /** @test */
    public function it_has_correct_fillable_attributes(): void
    {
        $logData = [
            'user_id' => $this->user->id,
            'email' => 'test@example.com',
            'ip' => '192.168.1.1',
        ];

        $log = Log::query()->create($logData);

        foreach ($logData as $key => $value) {
            $this->assertEquals($value, $log->$key);
        }
    }

    /** @test */
    public function it_belongs_to_a_user(): void
    {
        $log = Log::factory()->create(['user_id' => $this->user->id]);

        $this->assertInstanceOf(User::class, $log->user);
        $this->assertEquals($this->user->id, $log->user->id);
    }

    /** @test */
    public function it_stores_ip_addresses_correctly(): void
    {
        $ipAddresses = ['127.0.0.1', '192.168.1.100', '10.0.0.1'];

        foreach ($ipAddresses as $ip) {
            $log = Log::factory()->create(['ip' => $ip]);
            $this->assertEquals($ip, $log->ip);
        }
    }

    /** @test */
    public function it_orders_logs_by_creation_date(): void
    {
        $oldLog = Log::factory()->create(['created_at' => now()->subHours(2)]);
        $newLog = Log::factory()->create(['created_at' => now()]);

        $logs = Log::query()->latest()->get();

        $this->assertEquals($newLog->id, $logs->first()->id);
        $this->assertEquals($oldLog->id, $logs->last()->id);
    }
}
