use chrono::NaiveDate;
use paper_gap::arxiv::{self, PaperQuery};

#[test]
fn builds_query_with_category_and_date_range() {
    let query = arxiv::query_string(&PaperQuery {
        query: Some("symbolic computation".into()),
        category: Some("cs.PL".into()),
        from: Some(NaiveDate::from_ymd_opt(2026, 6, 1).unwrap()),
        to: Some(NaiveDate::from_ymd_opt(2026, 6, 29).unwrap()),
        since: None,
    })
    .unwrap();
    assert_eq!(
        query,
        "all:symbolic computation AND cat:cs.PL AND submittedDate:[202606010000 TO 202606292359]"
    );
}

#[test]
fn builds_arxiv_search_url() {
    let url = arxiv::search_url("cat:math.NA", 50);
    assert!(url.starts_with("https://export.arxiv.org/api/query?"));
    assert!(url.contains("search_query=cat%3Amath.NA"));
    assert!(url.contains("max_results=50"));
}

#[test]
fn rejects_missing_query_and_category() {
    let err = arxiv::query_string(&PaperQuery::default())
        .unwrap_err()
        .to_string();
    assert_eq!(err, "scan needs --query, --category, or both");
}

#[test]
fn parses_and_normalizes_arxiv_atom_xml() {
    let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:arxiv="http://arxiv.org/schemas/atom">
  <entry>
    <id>http://arxiv.org/abs/2603.21852v1</id>
    <updated>2026-03-29T12:34:56Z</updated>
    <published>2026-03-28T00:00:00Z</published>
    <title>  Fast FFT Methods
      for PDE Solvers </title>
    <summary> We present an FFT-based method for PDE simulation. </summary>
    <author><name>Ada Lovelace</name></author>
    <author><name>Alan Turing</name></author>
    <arxiv:doi>10.1234/example.doi</arxiv:doi>
    <category term="cs.PL" />
    <category term="math.NA" />
  </entry>
</feed>"#;
    let papers = arxiv::parse(xml).unwrap();
    assert_eq!(papers.len(), 1);
    let paper = &papers[0];
    assert_eq!(paper.id, "http://arxiv.org/abs/2603.21852v1");
    assert_eq!(paper.url, paper.id);
    assert_eq!(paper.arxiv_id.as_deref(), Some("2603.21852v1"));
    assert_eq!(paper.title, "Fast FFT Methods for PDE Solvers");
    assert_eq!(
        paper.abstract_text,
        "We present an FFT-based method for PDE simulation."
    );
    assert_eq!(paper.authors, vec!["Ada Lovelace", "Alan Turing"]);
    assert_eq!(
        paper.published_date.as_deref(),
        Some("2026-03-28T00:00:00Z")
    );
    assert_eq!(paper.updated_date.as_deref(), Some("2026-03-29T12:34:56Z"));
    assert_eq!(paper.doi.as_deref(), Some("10.1234/example.doi"));
    assert_eq!(paper.categories, vec!["cs.PL", "math.NA"]);
    assert_eq!(paper.source_provider, "arxiv");
    assert!(paper.extracted_methods.contains(&"FFT".to_string()));
    assert!(paper.extracted_methods.contains(&"PDE".to_string()));
}
