<?php

namespace Tests\Unit\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\Ticket;
use App\Models\TicketResponse;
use App\Models\User;
use Carbon\Carbon;
use Tests\TestCase;

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

        $this->user = User::factory()->create();
        $this->ticketData = [
            'user_id' => $this->user->id,
            'ticket_id' => 'TICKET-123456',
            'subject' => 'Test Subject',
            'message' => 'Test message content',
            'status' => 'pending',
            'ip_address' => '127.0.0.1',
            'last_response_at' => now(),
        ];
    }

    /** @test */
    public function it_can_create_a_ticket_with_factory(): void
    {
        $ticket = Ticket::factory()->create();

        $this->assertInstanceOf(Ticket::class, $ticket);
        $this->assertIsString($ticket->subject);
        $this->assertIsString($ticket->ticket_id);
    }

    /** @test */
    public function it_has_correct_fillable_attributes(): void
    {
        $ticket = Ticket::query()->create($this->ticketData);

        foreach ($this->ticketData as $key => $value) {
            if ($key === 'last_response_at') {
                // For datetime fields, check if it's an instance of Carbon
                $this->assertInstanceOf(Carbon::class, $ticket->$key);
            } else {
                $this->assertEquals($value, $ticket->$key);
            }
        }
    }

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

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

    /** @test */
    public function it_has_many_ticket_responses(): void
    {
        $ticket = Ticket::factory()->create();
        $response1 = TicketResponse::factory()->create(['ticket_id' => $ticket->id]);
        $response2 = TicketResponse::factory()->create(['ticket_id' => $ticket->id]);

        $this->assertCount(2, $ticket->responses);
        $this->assertContains($response1->id, $ticket->responses->pluck('id'));
        $this->assertContains($response2->id, $ticket->responses->pluck('id'));
    }

    /** @test */
    public function it_casts_last_response_at_to_datetime(): void
    {
        $ticket = Ticket::factory()->create([
            'last_response_at' => '2024-01-01 12:00:00',
        ]);

        $this->assertInstanceOf(Carbon::class, $ticket->last_response_at);
    }

    /** @test */
    public function it_uses_correct_table_name(): void
    {
        $ticket = new Ticket;

        $this->assertEquals('tickets', $ticket->getTable());
    }

    /** @test */
    public function it_extends_model_class(): void
    {
        $ticket = new Ticket;

        $this->assertInstanceOf(Model::class, $ticket);
    }
}
