<?php

namespace Tests\Unit\Models;

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

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

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

    /** @test */
    public function it_can_create_an_activation_key_with_factory(): void
    {
        $activationKey = ActivationKey::factory()->create();

        $this->assertInstanceOf(ActivationKey::class, $activationKey);
        $this->assertIsString($activationKey->activation_key);
        $this->assertIsInt($activationKey->price_id);
    }

    /** @test */
    public function it_has_correct_fillable_attributes(): void
    {
        $activationKeyData = [
            'user_id' => $this->user->id,
            'activation_key' => 'ACTIVATION-KEY-123456',
            'price_id' => 1,
            'is_activated' => false,
        ];

        $activationKey = ActivationKey::query()->create($activationKeyData);

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

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

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

    /** @test */
    public function it_generates_unique_keys(): void
    {
        $key1 = ActivationKey::factory()->create();
        $key2 = ActivationKey::factory()->create();

        $this->assertNotEquals($key1->activation_key, $key2->activation_key);
    }

    /** @test */
    public function it_can_query_unactivated_activation_keys(): void
    {
        ActivationKey::factory()->create(['is_activated' => false]);
        ActivationKey::factory()->create(['is_activated' => true]);

        $unactivatedKeys = ActivationKey::query()->where('is_activated', false)->get();
        $activatedKeys = ActivationKey::query()->where('is_activated', true)->get();

        $this->assertCount(1, $unactivatedKeys);
        $this->assertCount(1, $activatedKeys);
    }
}
