use lettre::message::{MultiPart, SinglePart};
use lettre::Message;
use mail_parser::MimeHeaders;
use std::error::Error;

/// Mock integration test validating that our SMTP serialization and IMAP parsing
/// logic functions cleanly without dropping or ignoring attributes, executing fully headless
/// without needing a binding live TCP/TLS external socket constraint.
#[test]
fn test_smtp_builder_and_imap_parser_mock() -> Result<(), Box<dyn Error>> {
    // 1. SMTP Mock Builder Simulation
    let sender = "alice@example.com";
    let receiver = "bob@example.com";
    let subject = "Mock Integration Payload";
    let body_text = "This is a body payload.";

    // Simulate Attachments
    let content = b"FILE_CONTENT_MOCK".to_vec();
    let attachment_name = "secret.txt";

    let email = Message::builder()
        .from(sender.parse()?)
        .to(receiver.parse()?)
        .subject(subject)
        .multipart(
            MultiPart::mixed()
                .singlepart(SinglePart::plain(body_text.to_string()))
                .singlepart(
                    SinglePart::builder()
                        .header(lettre::message::header::ContentType::parse("text/plain")?)
                        .header(lettre::message::header::ContentDisposition::attachment(
                            attachment_name,
                        ))
                        .body(content.clone()),
                ),
        )?;

    let raw_email_bytes = email.formatted();

    // 2. IMAP Mock Parsing Simulation (What we'd do on receiving bytes from IMAP FETCH)
    let parsed_message = mail_parser::MessageParser::default()
        .parse(&raw_email_bytes)
        .ok_or("Failed to parse raw email bytes")?;

    // Validate Headers
    assert_eq!(
        parsed_message.subject().unwrap(),
        "Mock Integration Payload"
    );

    let from_header = parsed_message.from().unwrap().first();
    assert_eq!(from_header.unwrap().address().unwrap(), "alice@example.com");

    let to_header = parsed_message.to().unwrap().first();
    assert_eq!(to_header.unwrap().address().unwrap(), "bob@example.com");

    // Validate Body
    assert_eq!(
        parsed_message.body_text(0).unwrap().trim(),
        "This is a body payload."
    );

    // Validate Attachments
    let mut attachment_found = false;
    for attachment in parsed_message.attachments() {
        if let Some(name) = attachment.attachment_name() {
            if name == attachment_name {
                attachment_found = true;
                assert_eq!(attachment.contents(), content.as_slice());
            }
        }
    }
    assert!(
        attachment_found,
        "Attachment was dropped during serialization/deserialization mock"
    );

    Ok(())
}
