<?php
declare(strict_types=1);

namespace FreshCloud\Mail\Tests\MimeParser;

use PHPUnit\Framework\TestCase;
use FreshCloud\Mail\MimeParser\SimpleMimeParser;
use FreshCloud\Mail\MimeParser\ParsedMessage;

final class SimpleMimeParserTest extends TestCase
{
    public function testParseSimpleTextEmail(): void
    {
        $raw = "From: john@example.com\r\n"
             . "To: jane@example.com\r\n"
             . "Subject: Hello World\r\n"
             . "Date: Mon, 21 Jul 2025 12:00:00 +0000\r\n"
             . "Content-Type: text/plain; charset=utf-8\r\n"
             . "\r\n"
             . "This is the body of the email.";

        $parser = new SimpleMimeParser();
        $msg = $parser->parse($raw);

        $this->assertInstanceOf(ParsedMessage::class, $msg);
        $this->assertEquals('Hello World', $msg->subject);
        $this->assertEquals('john@example.com', $msg->from->address);
        $this->assertCount(1, $msg->to);
        $this->assertEquals('jane@example.com', $msg->to[0]->address);
        $this->assertEquals('This is the body of the email.', $msg->textBody);
        $this->assertNull($msg->htmlBody);
        $this->assertCount(0, $msg->attachments);
    }

    public function testParseHtmlEmail(): void
    {
        $raw = "From: john@example.com\r\n"
             . "To: jane@example.com\r\n"
             . "Subject: HTML Test\r\n"
             . "Content-Type: text/html; charset=utf-8\r\n"
             . "\r\n"
             . "<h1>Hello</h1><p>World</p>";

        $parser = new SimpleMimeParser();
        $msg = $parser->parse($raw);

        $this->assertEquals('<h1>Hello</h1><p>World</p>', $msg->htmlBody);
    }

    public function testParseMultipartEmail(): void
    {
        $boundary = 'boundary123';
        $raw = "From: john@example.com\r\n"
             . "To: jane@example.com\r\n"
             . "Subject: Multipart Test\r\n"
             . "Content-Type: multipart/alternative; boundary=\"$boundary\"\r\n"
             . "\r\n"
             . "--$boundary\r\n"
             . "Content-Type: text/plain; charset=utf-8\r\n"
             . "\r\n"
             . "Plain text version.\r\n"
             . "--$boundary\r\n"
             . "Content-Type: text/html; charset=utf-8\r\n"
             . "\r\n"
             . "<p>HTML version.</p>\r\n"
             . "--$boundary--\r\n";

        $parser = new SimpleMimeParser();
        $msg = $parser->parse($raw);

        $this->assertEquals('Plain text version.', $msg->textBody);
        $this->assertEquals('<p>HTML version.</p>', $msg->htmlBody);
    }
}
