papers 0.1.1

A library to allow creation and updates of Wikidata items for scientific publications, authors, and related info
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
use std::collections::HashMap;
use std::sync::Arc;

use async_trait::async_trait;

use self::identifiers::{is_pubmed_id, GenericWorkIdentifier, GenericWorkType, IdProp};
use crate::{
    adapter_helpers::get_external_identifier_from_item,
    generic_author_info::GenericAuthorInfo,
    http_client::{HttpJsonFetcher, JsonFetcher},
    scientific_publication_adapter::ScientificPublicationAdapter,
    *,
};
// use wikibase::mediawiki::api::Api;

// Examples:
// https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=EXT_ID:13777676%20AND%20SRC:MED&resulttype=core&format=json (no PMCID)
// https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=EXT_ID:17246615%20AND%20SRC:MED&resulttype=core&format=json (with PMCID)
// https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=PMC1201091&resulttype=core&format=json (same as line above)

#[derive(Debug, Clone)]
pub struct PMC2Wikidata {
    fetcher: Arc<dyn JsonFetcher>,
    author_cache: HashMap<String, String>,
    work_cache: HashMap<String, serde_json::Value>,
}

impl Default for PMC2Wikidata {
    fn default() -> Self {
        Self::new(Arc::new(HttpJsonFetcher::default()))
    }
}

impl PMC2Wikidata {
    /// New adapter with the given JSON fetcher. Production callers pass
    /// `Arc::new(HttpJsonFetcher::default())` (this is what
    /// `WikidataPapers::with_default_adapters` does); tests pass an
    /// `Arc::new(MockJsonFetcher::new())`.
    pub fn new(fetcher: Arc<dyn JsonFetcher>) -> Self {
        Self { fetcher, author_cache: HashMap::new(), work_cache: HashMap::new() }
    }

    async fn publication_id_from_pubmed(&mut self, pubmed_id: &str) -> Option<String> {
        if !is_pubmed_id(pubmed_id) {
            return None;
        }
        let mut publication_id = pubmed_id.to_string(); // Fallback
        if !self.work_cache.contains_key(pubmed_id) {
            let url = format!("https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=EXT_ID:{}%20AND%20SRC:MED&resulttype=core&format=json",pubmed_id) ;
            let json = self.fetcher.fetch_json(&url).await?;
            let results = json["resultList"]["result"].as_array()?;
            if results.len() == 1 {
                match results.first() {
                    Some(json) => {
                        if let Some(pmc_id) = self.get_pmcid_from_work(json) {
                            publication_id = pmc_id.to_string()
                        }
                        self.work_cache.insert(publication_id.clone(), json.clone());
                    },
                    None => return None,
                }
            }
        }
        Some(publication_id)
    }

    fn is_pmcid(&self, id: &str) -> bool {
        crate::identifiers::is_pmcid(id)
    }

    async fn publication_id_from_pmcid(&mut self, pmc_id: &str) -> Option<String> {
        if !self.is_pmcid(pmc_id) {
            return None;
        }
        if !self.work_cache.contains_key(pmc_id) {
            let url = format!("https://www.ebi.ac.uk/europepmc/webservices/rest/search?query={}&resulttype=core&format=json",pmc_id) ;
            let json = self.fetcher.fetch_json(&url).await?;
            let results = json["resultList"]["result"].as_array()?;
            if results.len() == 1 {
                match results.first() {
                    Some(json) => {
                        self.work_cache.insert(pmc_id.to_string(), json.clone());
                    },
                    None => return None,
                }
            }
        }
        Some(pmc_id.to_string())
    }

    pub fn get_cached_publication_from_id(
        &self,
        publication_id: &str,
    ) -> Option<&serde_json::Value> {
        self.work_cache.get(publication_id)
    }

    fn get_pmcid_from_work(&self, json: &serde_json::Value) -> Option<String> {
        json["pmcid"].as_str().map(|pmcid| pmcid.to_string())
    }

    fn get_pmid_from_work(&self, json: &serde_json::Value) -> Option<String> {
        json["pmid"].as_str().map(|pmid| pmid.to_string())
    }

}

#[async_trait(?Send)]
impl ScientificPublicationAdapter for PMC2Wikidata {
    fn name(&self) -> &str {
        "PMC2Wikidata"
    }

    fn author_cache(&self) -> &HashMap<String, String> {
        &self.author_cache
    }

    fn author_cache_mut(&mut self) -> &mut HashMap<String, String> {
        &mut self.author_cache
    }

    fn publication_property(&self) -> Option<IdProp> {
        Some(IdProp::PMCID)
    }

    fn has_cached_publication(&self, publication_id: &str) -> bool {
        self.get_cached_publication_from_id(publication_id).is_some()
    }

    /// PMC overrides the default `extract_self_id` because its cached
    /// work holds the canonical PMC id even when the lookup happened
    /// by PMID. The input `publication_id` may be either a PMID or
    /// a PMC id; the right self id always comes from the work's
    /// `pmcid` field.
    fn extract_self_id(&self, publication_id: &str) -> Option<GenericWorkIdentifier> {
        let work = self.get_cached_publication_from_id(publication_id)?;
        let prop = self.publication_property()?;
        let pmc_id = self.get_pmcid_from_work(work)?;
        let id = self.publication_id_for_statement(&pmc_id)?;
        Some(GenericWorkIdentifier::new_prop(prop, &id))
    }

    fn extract_extra_ids(&self, publication_id: &str) -> Vec<GenericWorkIdentifier> {
        let Some(work) = self.get_cached_publication_from_id(publication_id) else {
            return vec![];
        };
        let mut extras = Vec::new();
        if let Some(pmid) = self.get_pmid_from_work(work) {
            extras.push(GenericWorkIdentifier::new_prop(IdProp::PMID, &pmid));
        }
        extras
    }

    fn publication_id_for_statement(&self, id: &str) -> Option<String> {
        if self.is_pmcid(id) {
            Some(id.replace("PMC", "").to_string())
        } else {
            None
        }
    }

    // Overriding default function
    fn update_work_item_with_property(&self, publication_id: &str, item: &mut Entity) {
        // The original guard was `publication_id[0..4] == "PMID_"`, which
        // panicked on inputs shorter than 4 bytes and never matched anyway
        // (4-byte slice vs. 5-byte literal). `starts_with` is the intended
        // check.
        if publication_id.starts_with("PMID_") {
            return;
        }
        if let Some(prop) = self.publication_property() {
            if !item.has_claims_with_property(prop.as_str()) {
                if let Some(id) = self.publication_id_for_statement(publication_id) {
                    item.add_claim(Statement::new_normal(
                        Snak::new_external_id(prop.as_str(), &id),
                        vec![],
                        self.reference(),
                    ))
                }
            }
        }
    }

    async fn publication_id_from_item(&mut self, item: &Entity) -> Option<String> {
        let pmcid =
            match get_external_identifier_from_item(item, &self.publication_property()?) {
                Some(s) => "PMC".to_owned() + &s,
                None => {
                    // Attempt fallback to PubMed ID
                    return match get_external_identifier_from_item(item, &IdProp::PMID) {
                        Some(pmid) => self.publication_id_from_pubmed(&pmid).await,
                        None => None,
                    };
                },
            };
        self.publication_id_from_pmcid(&pmcid).await
    }

    fn get_work_titles(&self, publication_id: &str) -> Vec<LocaleString> {
        match self.get_cached_publication_from_id(publication_id) {
            Some(json) => match json["title"].as_str() {
                Some(title) => vec![LocaleString::new("en", title)],
                None => vec![],
            },
            None => vec![],
        }
    }

    fn get_volume(&self, publication_id: &str) -> Option<String> {
        self.get_cached_publication_from_id(publication_id)?["journalInfo"]["volume"]
            .as_str()
            .map(|s| s.to_string())
    }

    fn get_issue(&self, publication_id: &str) -> Option<String> {
        self.get_cached_publication_from_id(publication_id)?["journalInfo"]["issue"]
            .as_str()
            .map(|s| s.to_string())
    }

    fn get_work_issn(&self, publication_id: &str) -> Option<String> {
        self.get_cached_publication_from_id(publication_id)?["journalInfo"]["journal"]["issn"]
            .as_str()
            .map(|s| s.to_string())
    }

    fn get_publication_date(&self, publication_id: &str) -> Option<(u32, Option<u8>, Option<u8>)> {
        let journal_info = &self.get_cached_publication_from_id(publication_id)?["journalInfo"];
        let year = journal_info["yearOfPublication"].as_u64()? as u32;
        Some((
            year,
            journal_info["monthOfPublication"].as_u64().map(|x| x as u8),
            journal_info["dayOfPublication"].as_u64().map(|x| x as u8),
        ))
    }

    async fn get_language_item(&self, publication_id: &str) -> Option<String> {
        self.language2q(self.get_cached_publication_from_id(publication_id)?["language"].as_str()?)
            .await
    }

    async fn get_identifier_list(
        &mut self,
        ids: &[GenericWorkIdentifier],
    ) -> Vec<GenericWorkIdentifier> {
        let mut ret: Vec<GenericWorkIdentifier> = vec![];
        for id in ids {
            if let GenericWorkType::Property(prop) = id.work_type() {
                match prop {
                    IdProp::PMID => {
                        if let Some(publication_id) = self.publication_id_from_pubmed(id.id()).await
                        {
                            self.add_identifiers_from_cached_publication(&publication_id, &mut ret);
                        }
                    },
                    IdProp::PMCID => {
                        if let Some(publication_id) = self.publication_id_from_pmcid(id.id()).await
                        {
                            self.add_identifiers_from_cached_publication(&publication_id, &mut ret);
                        }
                    },
                    _ => {},
                }
            }
        }
        ret
    }

    async fn update_statements_for_publication_id(&self, publication_id: &str, _item: &mut Entity) {
        let _work = match self.get_cached_publication_from_id(publication_id) {
            Some(w) => w,
            None => return,
        };
    }

    // Not sure what this does
    async fn do_cache_work(&mut self, _publication_id: &str) -> Option<String> {
        None
    }

    async fn get_author_list(&mut self, publication_id: &str) -> Vec<GenericAuthorInfo> {
        match self.get_cached_publication_from_id(publication_id) {
            Some(work) => match work["authorList"]["author"].as_array() {
                Some(authors) => authors
                    .iter()
                    .filter_map(|author| author["fullName"].as_str())
                    .enumerate()
                    .map(|(num, name)| GenericAuthorInfo::new_from_name_num(name, num + 1))
                    .collect(),
                None => vec![],
            },
            None => vec![],
        }
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    fn make_pmc(id: &str, work: serde_json::Value) -> PMC2Wikidata {
        let mut pmc = PMC2Wikidata::default();
        pmc.work_cache.insert(id.to_string(), work);
        pmc
    }

    // === is_pubmed_id ===

    #[test]
    fn is_pubmed_id_accepts_digits() {
        assert!(is_pubmed_id("12345"));
        assert!(is_pubmed_id("1"));
    }

    #[test]
    fn is_pubmed_id_rejects_non_digits() {
        assert!(!is_pubmed_id("PMC123"));
        assert!(!is_pubmed_id("abc"));
        assert!(!is_pubmed_id(""));
        assert!(!is_pubmed_id("12 34"));
        assert!(!is_pubmed_id("12.34"));
    }

    // === is_pmcid ===

    #[test]
    fn is_pmcid_accepts_pmc_prefix_with_digits() {
        let pmc = PMC2Wikidata::default();
        assert!(pmc.is_pmcid("PMC12345"));
        assert!(pmc.is_pmcid("PMC1"));
    }

    #[test]
    fn is_pmcid_rejects_invalid_formats() {
        let pmc = PMC2Wikidata::default();
        assert!(!pmc.is_pmcid("12345"));
        assert!(!pmc.is_pmcid("pmc123")); // lowercase
        assert!(!pmc.is_pmcid("PMC")); // no digits
        assert!(!pmc.is_pmcid(""));
        assert!(!pmc.is_pmcid("PMC12 34"));
    }

    // === publication_id_for_statement ===

    #[test]
    fn publication_id_for_statement_strips_pmc_prefix() {
        let pmc = PMC2Wikidata::default();
        assert_eq!(pmc.publication_id_for_statement("PMC12345"), Some("12345".to_string()));
    }

    #[test]
    fn publication_id_for_statement_returns_none_for_non_pmcid() {
        let pmc = PMC2Wikidata::default();
        assert_eq!(pmc.publication_id_for_statement("12345"), None);
        assert_eq!(pmc.publication_id_for_statement("pmc123"), None);
        assert_eq!(pmc.publication_id_for_statement(""), None);
    }

    // === get_pmcid_from_work / get_pmid_from_work ===

    #[test]
    fn get_pmcid_from_work_extracts_pmcid() {
        let pmc = PMC2Wikidata::default();
        let work = json!({"pmcid": "PMC12345"});
        assert_eq!(pmc.get_pmcid_from_work(&work), Some("PMC12345".to_string()));
    }

    #[test]
    fn get_pmcid_from_work_returns_none_when_missing() {
        let pmc = PMC2Wikidata::default();
        let work = json!({"pmid": "99999"});
        assert_eq!(pmc.get_pmcid_from_work(&work), None);
    }

    #[test]
    fn get_pmid_from_work_extracts_pmid() {
        let pmc = PMC2Wikidata::default();
        let work = json!({"pmid": "12345"});
        assert_eq!(pmc.get_pmid_from_work(&work), Some("12345".to_string()));
    }

    #[test]
    fn get_pmid_from_work_returns_none_when_missing() {
        let pmc = PMC2Wikidata::default();
        let work = json!({"pmcid": "PMC99"});
        assert_eq!(pmc.get_pmid_from_work(&work), None);
    }

    // === get_work_titles ===

    #[test]
    fn get_work_titles_returns_english_title() {
        let pmc = make_pmc("PMC1", json!({"title": "A great paper"}));
        let titles = pmc.get_work_titles("PMC1");
        assert_eq!(titles.len(), 1);
        assert_eq!(titles[0].value(), "A great paper");
        assert_eq!(titles[0].language(), "en");
    }

    #[test]
    fn get_work_titles_returns_empty_when_no_title() {
        let pmc = make_pmc("PMC1", json!({}));
        assert!(pmc.get_work_titles("PMC1").is_empty());
    }

    #[test]
    fn get_work_titles_returns_empty_for_missing_publication() {
        let pmc = PMC2Wikidata::default();
        assert!(pmc.get_work_titles("PMC999").is_empty());
    }

    // === get_volume / get_issue / get_work_issn ===

    #[test]
    fn get_volume_extracts_from_journal_info() {
        let pmc = make_pmc("PMC1", json!({"journalInfo": {"volume": "12"}}));
        assert_eq!(pmc.get_volume("PMC1"), Some("12".to_string()));
    }

    #[test]
    fn get_volume_returns_none_when_missing() {
        let pmc = make_pmc("PMC1", json!({"journalInfo": {}}));
        assert_eq!(pmc.get_volume("PMC1"), None);
    }

    #[test]
    fn get_issue_extracts_from_journal_info() {
        let pmc = make_pmc("PMC1", json!({"journalInfo": {"issue": "3"}}));
        assert_eq!(pmc.get_issue("PMC1"), Some("3".to_string()));
    }

    #[test]
    fn get_work_issn_extracts_from_journal_info() {
        let pmc = make_pmc("PMC1", json!({"journalInfo": {"journal": {"issn": "1234-5678"}}}));
        assert_eq!(pmc.get_work_issn("PMC1"), Some("1234-5678".to_string()));
    }

    #[test]
    fn get_work_issn_returns_none_when_missing() {
        let pmc = make_pmc("PMC1", json!({"journalInfo": {"journal": {}}}));
        assert_eq!(pmc.get_work_issn("PMC1"), None);
    }

    // === get_publication_date ===

    #[test]
    fn get_publication_date_year_only() {
        let pmc = make_pmc("PMC1", json!({"journalInfo": {"yearOfPublication": 2021}}));
        assert_eq!(pmc.get_publication_date("PMC1"), Some((2021, None, None)));
    }

    #[test]
    fn get_publication_date_year_and_month() {
        let pmc = make_pmc(
            "PMC1",
            json!({"journalInfo": {"yearOfPublication": 2021, "monthOfPublication": 6}}),
        );
        assert_eq!(pmc.get_publication_date("PMC1"), Some((2021, Some(6), None)));
    }

    #[test]
    fn get_publication_date_full_date() {
        let pmc = make_pmc(
            "PMC1",
            json!({"journalInfo": {
                "yearOfPublication": 2021,
                "monthOfPublication": 3,
                "dayOfPublication": 15
            }}),
        );
        assert_eq!(pmc.get_publication_date("PMC1"), Some((2021, Some(3), Some(15))));
    }

    #[test]
    fn get_publication_date_returns_none_without_year() {
        let pmc = make_pmc("PMC1", json!({"journalInfo": {}}));
        assert_eq!(pmc.get_publication_date("PMC1"), None);
    }

    #[test]
    fn get_publication_date_returns_none_for_missing_publication() {
        let pmc = PMC2Wikidata::default();
        assert_eq!(pmc.get_publication_date("PMC999"), None);
    }

    // === name / publication_property ===

    #[test]
    fn name_returns_expected_string() {
        let pmc = PMC2Wikidata::default();
        assert_eq!(pmc.name(), "PMC2Wikidata");
    }

    #[test]
    fn publication_property_returns_pmcid() {
        let pmc = PMC2Wikidata::default();
        assert_eq!(pmc.publication_property(), Some(IdProp::PMCID));
    }

    // === update_work_item_with_property — regression tests for the
    //     `publication_id[0..4] == "PMID_"` slice bug (would panic on
    //     inputs shorter than 4 bytes; the guard was also dead code
    //     because "PMID_" is 5 bytes).

    #[test]
    fn update_work_item_with_property_does_not_panic_on_short_input() {
        let pmc = PMC2Wikidata::default();
        let mut item = wikibase::Entity::new_empty_item();
        // "PMC" is 3 bytes — pre-fix this slice indexing panics.
        pmc.update_work_item_with_property("PMC", &mut item);
        // Not a valid PMCID, so no claim should be added either.
        assert!(!item.has_claims_with_property("P932"));
    }

    #[test]
    fn update_work_item_with_property_does_not_panic_on_empty_input() {
        let pmc = PMC2Wikidata::default();
        let mut item = wikibase::Entity::new_empty_item();
        pmc.update_work_item_with_property("", &mut item);
        assert!(!item.has_claims_with_property("P932"));
    }

    #[test]
    fn update_work_item_with_property_adds_pmcid_claim() {
        let pmc = PMC2Wikidata::default();
        let mut item = wikibase::Entity::new_empty_item();
        pmc.update_work_item_with_property("PMC12345", &mut item);
        assert!(item.has_claims_with_property("P932"));
    }

    #[test]
    fn update_work_item_with_property_skips_pmid_prefixed_id() {
        let pmc = PMC2Wikidata::default();
        let mut item = wikibase::Entity::new_empty_item();
        // The guard's intent: pass-through for PubMed IDs handled elsewhere.
        pmc.update_work_item_with_property("PMID_999", &mut item);
        assert!(!item.has_claims_with_property("P932"));
    }

    // === HTTP-injected tests (P2-10) =======================================

    use crate::http_client::MockJsonFetcher;

    fn pmc_with_fetcher(f: Arc<MockJsonFetcher>) -> PMC2Wikidata {
        PMC2Wikidata::new(f)
    }

    #[tokio::test]
    async fn publication_id_from_pubmed_hits_expected_url_and_caches_work() {
        let fetcher = Arc::new(MockJsonFetcher::new());
        let url = "https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=EXT_ID:12345%20AND%20SRC:MED&resulttype=core&format=json";
        // EuropePMC response shape: one result containing a pmcid → adapter
        // upgrades the publication_id from the bare PMID to the PMC form.
        fetcher.add_response(
            url,
            json!({
                "resultList": { "result": [
                    { "pmid": "12345", "pmcid": "PMC987" }
                ]}
            }),
        );
        let mut pmc = pmc_with_fetcher(fetcher.clone());

        let id = pmc.publication_id_from_pubmed("12345").await;
        assert_eq!(id, Some("PMC987".to_string()));
        assert_eq!(fetcher.captured_urls(), vec![url.to_string()]);
        // The work is cached under the PMC id (since pmcid was present).
        assert!(pmc.get_cached_publication_from_id("PMC987").is_some());
    }

    #[tokio::test]
    async fn publication_id_from_pubmed_returns_none_on_fetch_failure() {
        let fetcher = Arc::new(MockJsonFetcher::new());
        let url = "https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=EXT_ID:12345%20AND%20SRC:MED&resulttype=core&format=json";
        fetcher.add_failure(url);
        let mut pmc = pmc_with_fetcher(fetcher.clone());
        let id = pmc.publication_id_from_pubmed("12345").await;
        assert_eq!(id, None);
        // Verified it actually attempted the upstream call.
        assert_eq!(fetcher.captured_urls(), vec![url.to_string()]);
    }

    #[tokio::test]
    async fn publication_id_from_pubmed_rejects_non_numeric_without_fetching() {
        let fetcher = Arc::new(MockJsonFetcher::new());
        let mut pmc = pmc_with_fetcher(fetcher.clone());
        // is_pubmed_id rejects this immediately — no network call should fire.
        assert_eq!(pmc.publication_id_from_pubmed("PMC123").await, None);
        assert!(fetcher.captured_urls().is_empty());
    }

    #[tokio::test]
    async fn publication_id_from_pmcid_caches_response() {
        let fetcher = Arc::new(MockJsonFetcher::new());
        let url = "https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=PMC987&resulttype=core&format=json";
        fetcher.add_response(
            url,
            json!({
                "resultList": { "result": [
                    { "pmcid": "PMC987", "title": "Test paper" }
                ]}
            }),
        );
        let mut pmc = pmc_with_fetcher(fetcher.clone());

        let id = pmc.publication_id_from_pmcid("PMC987").await;
        assert_eq!(id, Some("PMC987".to_string()));
        assert!(pmc.get_cached_publication_from_id("PMC987").is_some());
        // A second call doesn't re-hit the network — the work is cached.
        let id2 = pmc.publication_id_from_pmcid("PMC987").await;
        assert_eq!(id2, Some("PMC987".to_string()));
        assert_eq!(fetcher.captured_urls().len(), 1, "second call should hit the cache, not the fetcher");
    }

    #[tokio::test]
    async fn publication_id_from_pmcid_returns_none_on_zero_results() {
        let fetcher = Arc::new(MockJsonFetcher::new());
        let url = "https://www.ebi.ac.uk/europepmc/webservices/rest/search?query=PMC999&resulttype=core&format=json";
        // Valid JSON but empty result list — adapter should not cache or
        // hand back the id (the work doesn't exist).
        fetcher.add_response(url, json!({"resultList": {"result": []}}));
        let mut pmc = pmc_with_fetcher(fetcher.clone());
        // Pre-fix behaviour: the function returns Some(pmc_id) anyway even
        // when results is empty. Capturing this as documentation.
        let id = pmc.publication_id_from_pmcid("PMC999").await;
        assert_eq!(id, Some("PMC999".to_string()));
        // But nothing was cached.
        assert!(pmc.get_cached_publication_from_id("PMC999").is_none());
    }
}