<?php

declare(strict_types=1);

namespace Tests\Unit\Services;

use App\Services\NoteService;
use App\Services\LeadService;
use Tests\TestCase;

class NoteServiceTest extends TestCase
{
    private NoteService $noteService;
    private LeadService $leadService;
    private int $userId;
    private int $eventId;

    protected function setUp(): void
    {
        parent::setUp();
        $this->noteService = new NoteService();
        $this->leadService = new LeadService();
        $this->userId = $this->createTestUser('gestor@test.com', 'comercial_manager', 'active');
        $this->eventId = $this->createTestEvent('Feria Notes', $this->userId);
    }

    private function createLead(): int
    {
        $lead = $this->leadService->createManual([
            'first_name' => 'Nota', 'last_name' => 'Test', 'email' => 'nota@test.com',
        ], $this->userId, $this->eventId);
        return $lead['id'];
    }

    public function testCreateTextNote(): void
    {
        $leadId = $this->createLead();
        $note = $this->noteService->createTextNote($leadId, 'Nota de prueba', $this->userId);

        $this->assertEquals('texto', $note['type']);
        $this->assertEquals('Nota de prueba', $note['content']);
        $this->assertEquals($leadId, $note['lead_id']);
    }

    public function testCreateTextNoteEmptyContent(): void
    {
        $leadId = $this->createLead();

        $this->expectException(\RuntimeException::class);
        $this->noteService->createTextNote($leadId, '', $this->userId);
    }

    public function testGetNotesByLead(): void
    {
        $leadId = $this->createLead();
        $this->noteService->createTextNote($leadId, 'Nota 1', $this->userId);
        $this->noteService->createTextNote($leadId, 'Nota 2', $this->userId);

        $notes = $this->noteService->getNotesByLead($leadId);
        $this->assertCount(2, $notes);
    }

    public function testGetNotesByLeadEmpty(): void
    {
        $leadId = $this->createLead();
        $notes = $this->noteService->getNotesByLead($leadId);
        $this->assertEmpty($notes);
    }

    public function testDeleteNote(): void
    {
        $leadId = $this->createLead();
        $note = $this->noteService->createTextNote($leadId, 'Para eliminar', $this->userId);

        $this->noteService->deleteNote($note['id']);

        $notes = $this->noteService->getNotesByLead($leadId);
        $this->assertCount(0, $notes);
    }

    public function testDeleteNoteNotFound(): void
    {
        $this->expectException(\RuntimeException::class);
        $this->noteService->deleteNote(9999);
    }
}
