<?php

namespace Tests\Unit\Models;

use App\Models\PremiumEmail;
use App\Models\User;
use Carbon\Carbon;
use Tests\TestCase;

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

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

    /** @test */
    public function it_can_create_a_premium_email_with_factory(): void
    {
        $premiumEmail = PremiumEmail::factory()->create();

        $this->assertInstanceOf(PremiumEmail::class, $premiumEmail);
        $this->assertIsString($premiumEmail->from_email);
        $this->assertIsString($premiumEmail->subject);
    }

    /** @test */
    public function it_has_correct_fillable_attributes(): void
    {
        $premiumEmailData = [
            'user_id' => $this->user->id,
            'message_id' => 'test_msg_123',
            'from_email' => 'sender@example.com',
            'from_name' => 'Test Sender',
            'subject' => 'Test Subject',
            'to' => ['recipient@example.com'],
        ];

        $premiumEmail = PremiumEmail::query()->create($premiumEmailData);

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

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

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

    /** @test */
    public function it_casts_timestamp_to_datetime(): void
    {
        $timestamp = now()->subDays(5);
        $premiumEmail = PremiumEmail::factory()->create(['timestamp' => $timestamp]);

        $this->assertInstanceOf(Carbon::class, $premiumEmail->timestamp);
        $this->assertEquals($timestamp->format('Y-m-d H:i:s'), $premiumEmail->timestamp->format('Y-m-d H:i:s'));
    }

    /** @test */
    public function it_can_query_seen_and_unseen_emails(): void
    {
        PremiumEmail::factory()->create(['is_seen' => true]);
        PremiumEmail::factory()->create(['is_seen' => false]);

        $seenEmails = PremiumEmail::query()->where('is_seen', true)->get();
        $unseenEmails = PremiumEmail::query()->where('is_seen', false)->get();

        $this->assertCount(1, $seenEmails);
        $this->assertCount(1, $unseenEmails);
    }
}
