import 'package:flutter_test/flutter_test.dart';
import 'package:tane/domain/species_reference_links.dart';

void main() {
  test('all identifiers present yields gbif, wikipedia and wikispecies', () {
    final links = speciesReferenceLinks(
      scientificName: 'Solanum lycopersicum',
      gbifKey: 2930137,
      wikidataQid: 'Q23501',
      languageCode: 'es',
    );
    expect(links.map((l) => l.source), [
      ReferenceSource.gbif,
      ReferenceSource.wikipedia,
      ReferenceSource.wikispecies,
    ]);
    expect(links[0].url, 'https://www.gbif.org/species/2930137');
    expect(
      links[1].url,
      'https://www.wikidata.org/wiki/Special:GoToLinkedPage/eswiki/Q23501',
    );
    expect(
      links[2].url,
      'https://species.wikimedia.org/wiki/Solanum_lycopersicum',
    );
  });

  test('wikipedia link is locale-aware', () {
    String wiki(String lang) => speciesReferenceLinks(
      scientificName: 'Zea mays',
      wikidataQid: 'Q11575',
      languageCode: lang,
    ).firstWhere((l) => l.source == ReferenceSource.wikipedia).url;

    expect(wiki('en'), contains('/enwiki/Q11575'));
    expect(wiki('ar'), contains('/arwiki/Q11575'));
  });

  test('locale region and case are normalised to the bare wiki subtag', () {
    String wiki(String lang) => speciesReferenceLinks(
      scientificName: 'Zea mays',
      wikidataQid: 'Q11575',
      languageCode: lang,
    ).firstWhere((l) => l.source == ReferenceSource.wikipedia).url;

    expect(wiki('pt_BR'), contains('/ptwiki/'));
    expect(wiki('zh-Hans'), contains('/zhwiki/'));
    expect(wiki('EN'), contains('/enwiki/'));
    expect(wiki(''), contains('/enwiki/')); // empty locale → English
  });

  test('a missing identifier simply drops that source', () {
    final onlyGbif = speciesReferenceLinks(
      scientificName: '', // no wikispecies without a name
      gbifKey: 42,
    );
    expect(onlyGbif.map((l) => l.source), [ReferenceSource.gbif]);

    final blankQid = speciesReferenceLinks(
      scientificName: 'Daucus carota',
      wikidataQid: '  ',
    );
    expect(
      blankQid.map((l) => l.source),
      isNot(contains(ReferenceSource.wikipedia)),
    );
    expect(blankQid.map((l) => l.source), [ReferenceSource.wikispecies]);
  });

  test('nothing identifiable yields no links', () {
    expect(speciesReferenceLinks(scientificName: '   '), isEmpty);
  });

  test('scientific names with spaces and diacritics are URL-safe', () {
    final link = speciesReferenceLinks(
      scientificName: 'Allium × proliferum',
    ).single;
    expect(link.source, ReferenceSource.wikispecies);
    expect(
      link.url,
      'https://species.wikimedia.org/wiki/Allium_%C3%97_proliferum',
    );
  });
}
