use rogue_agenda::{
    Database,
    model::{ItemChanges, ViewKind},
};
use tempfile::tempdir;

fn all_items(database: &Database) -> rogue_agenda::model::ViewDef {
    database
        .views()
        .unwrap()
        .into_iter()
        .find(|view| view.kind == ViewKind::List)
        .unwrap()
}

#[test]
fn completing_a_recurring_item_preserves_wall_time() {
    let directory = tempdir().unwrap();
    let path = directory.path().join("recurring.agnd");
    let mut database = Database::open(&path).unwrap();
    let item = database.add_item("Weekly review").unwrap();
    database
        .update_item(
            item,
            &ItemChanges {
                when_at: Some(Some("2026-09-01T14:30:00+00:00".into())),
                recurrence: Some("weekly".into()),
                ..ItemChanges::default()
            },
        )
        .unwrap();

    database.toggle_done(&[item]).unwrap();

    let items = database.items(&all_items(&database), "").unwrap();
    let next = items.iter().find(|candidate| candidate.id != item).unwrap();
    assert!(
        next.when_at
            .as_deref()
            .unwrap()
            .contains("2026-09-08T14:30:00")
    );
}

#[test]
fn completed_recurring_ical_roundtrip_does_not_create_a_duplicate() {
    let directory = tempdir().unwrap();
    let source_path = directory.path().join("source.agnd");
    let mut source = Database::open(&source_path).unwrap();
    let item = source.add_item("Prepare launch").unwrap();
    source
        .update_item(
            item,
            &ItemChanges {
                when_at: Some(Some("2026-09-01T14:30:00+00:00".into())),
                recurrence: Some("every 2 weeks".into()),
                ..ItemChanges::default()
            },
        )
        .unwrap();
    source.toggle_done(&[item]).unwrap();

    let export_path = directory.path().join("tasks.ics");
    source.export("ics", &export_path, None).unwrap();

    let target_path = directory.path().join("target.agnd");
    let mut target = Database::open(&target_path).unwrap();
    assert_eq!(target.import_path(&export_path).unwrap(), 2);
    assert_eq!(target.items(&all_items(&target), "").unwrap().len(), 2);
}
