use forgejo_api::structs::*;

mod common;

use common::{basic_org_repo, basic_repo, Git};
use futures::{StreamExt, TryStreamExt};

#[tokio::test]
async fn pull_request() {
    let api = common::login();

    let git = Git::new("./test_repos/pr");
    let _ = basic_repo(&api, &git, "pr-test").await;
    git.run(&["switch", "-c", "test"]);

    tokio::fs::write(
        "./test_repos/pr/example.rs",
        "fn add_one(x: u32) -> u32 { x + 1 }",
    )
    .await
    .unwrap();
    git.run(&["add", "."]);
    git.run(&["commit", "-m", "egg"]);
    git.run(&["push", "-u", "origin", "test"]);

    let pr_opt = CreatePullRequestOption {
        assignee: None,
        assignees: Some(vec!["TestingAdmin".into()]),
        base: Some("main".into()),
        body: Some("This is a test PR".into()),
        due_date: None,
        head: Some("test".into()),
        labels: None,
        milestone: None,
        title: Some("test pr".into()),
    };

    // Wait for... something to happen, or else creating a PR will return 404
    tokio::time::sleep(std::time::Duration::from_secs(3)).await;
    let pr = api
        .repo_create_pull_request("TestingAdmin", "pr-test", pr_opt)
        .await
        .expect("couldn't create pr");

    let is_merged = api
        .repo_pull_request_is_merged("TestingAdmin", "pr-test", pr.number.unwrap())
        .await
        .is_ok();
    assert!(!is_merged, "pr should not yet be merged");

    let pr_files_query = RepoGetPullRequestFilesQuery::default();
    let (_, _) = api
        .repo_get_pull_request_files(
            "TestingAdmin",
            "pr-test",
            pr.number.unwrap(),
            pr_files_query,
        )
        .await
        .unwrap();

    let merge_opt = MergePullRequestOption {
        r#do: MergePullRequestOptionDo::Merge,
        merge_commit_id: None,
        merge_message_field: None,
        merge_title_field: None,
        delete_branch_after_merge: Some(true),
        force_merge: None,
        head_commit_id: None,
        merge_when_checks_succeed: None,
    };

    api.repo_merge_pull_request("TestingAdmin", "pr-test", pr.number.unwrap(), merge_opt)
        .await
        .expect("couldn't merge pr");
    let is_merged = api
        .repo_pull_request_is_merged("TestingAdmin", "pr-test", pr.number.unwrap())
        .await
        .is_ok();
    assert!(is_merged, "pr should be merged");
}

#[tokio::test]
async fn release() {
    let api = common::login();

    let git = Git::new("./test_repos/release");
    let _ = basic_repo(&api, &git, "release-test").await;

    // Wait for the repo to be finished being populated, or else creating a
    // release will return "422 repo is empty"
    tokio::time::sleep(std::time::Duration::from_secs(3)).await;

    let query = RepoListReleasesQuery::default();
    assert!(
        api.repo_list_releases("TestingAdmin", "release-test", query)
            .await
            .unwrap()
            .1
            .is_empty(),
        "there should be no releases yet"
    );

    let tag_opt = CreateTagOption {
        message: Some("This is a tag!".into()),
        tag_name: "v1.0".into(),
        target: None,
    };
    api.repo_create_tag("TestingAdmin", "release-test", tag_opt)
        .await
        .expect("failed to create tag");

    let release_opt = CreateReleaseOption {
        body: Some("This is a release!".into()),
        draft: Some(true),
        name: Some("v1.0".into()),
        prerelease: Some(false),
        tag_name: "v1.0".into(),
        target_commitish: None,
        hide_archive_links: None,
    };
    let release = api
        .repo_create_release("TestingAdmin", "release-test", release_opt)
        .await
        .expect("failed to create release");
    let edit_release = EditReleaseOption {
        body: None,
        draft: Some(false),
        name: None,
        prerelease: None,
        tag_name: None,
        target_commitish: None,
        hide_archive_links: None,
    };
    api.repo_edit_release(
        "TestingAdmin",
        "release-test",
        release.id.unwrap(),
        edit_release,
    )
    .await
    .expect("failed to edit release");

    let release_by_tag = api
        .repo_get_release_by_tag("TestingAdmin", "release-test", "v1.0")
        .await
        .expect("failed to find release");
    let release_latest = api
        .repo_get_latest_release("TestingAdmin", "release-test")
        .await
        .expect("failed to find latest release");
    assert!(release_by_tag == release_latest, "releases not equal");

    let attachment = api
        .repo_create_release_attachment(
            "TestingAdmin",
            "release-test",
            release.id.unwrap(),
            Some(b"This is a file!"),
            None,
            RepoCreateReleaseAttachmentQuery {
                name: Some("test.txt".into()),
            },
        )
        .await
        .expect("failed to create release attachment");
    assert!(
        &*api
            .download_release_attachment(
                "TestingAdmin",
                "release-test",
                release.id.unwrap(),
                attachment.id.unwrap()
            )
            .await
            .unwrap()
            == b"This is a file!",
        "couldn't download attachment"
    );
    let _zip_archive = api
        .repo_get_archive("TestingAdmin", "release-test", "v1.0.zip")
        .await
        .unwrap();
    let _tar_archive = api
        .repo_get_archive("TestingAdmin", "release-test", "v1.0.tar.gz")
        .await
        .unwrap();
    // check these contents when their return value is fixed

    api.repo_delete_release_attachment(
        "TestingAdmin",
        "release-test",
        release.id.unwrap(),
        attachment.id.unwrap(),
    )
    .await
    .expect("failed to deleted attachment");

    api.repo_delete_release("TestingAdmin", "release-test", release.id.unwrap())
        .await
        .expect("failed to delete release");

    api.repo_delete_tag("TestingAdmin", "release-test", "v1.0")
        .await
        .expect("failed to delete release");
}

#[tokio::test]
async fn delete_repo() {
    let api = common::login();
    let git = Git::new("./test_repos/delete");
    let _ = basic_repo(&api, &git, "delete-test").await;

    api.repo_delete("TestingAdmin", "delete-test")
        .await
        .expect("failed to delete repo");
}

#[tokio::test]
async fn team_pr_review_request() {
    let api = common::login();

    let org_opt = CreateOrgOption {
        description: Some("Testing team review requests".into()),
        email: None,
        full_name: None,
        location: None,
        repo_admin_change_team_access: None,
        username: "team-review-org".into(),
        visibility: None,
        website: None,
    };
    api.org_create(org_opt).await.unwrap();

    let git = Git::new("./test_repos/team-pr-review");
    let _ = basic_org_repo(&api, &git, "team-review-org", "team-pr-review").await;

    git.run(&["switch", "-c", "test"]);
    tokio::fs::write(
        "./test_repos/team-pr-review/example.rs",
        "fn add_one(x: u32) -> u32 { x + 1 }",
    )
    .await
    .unwrap();
    git.run(&["add", "."]);
    git.run(&["commit", "-m", "egg"]);
    git.run(&["push", "-u", "origin", "test"]);

    let pr_opt = CreatePullRequestOption {
        assignee: None,
        assignees: Some(vec!["TestingAdmin".into()]),
        base: Some("main".into()),
        body: Some("This is a test PR".into()),
        due_date: None,
        head: Some("test".into()),
        labels: None,
        milestone: None,
        title: Some("test pr".into()),
    };

    // Wait for... something to happen, or else creating a PR will return 404
    tokio::time::sleep(std::time::Duration::from_secs(3)).await;
    api.repo_create_pull_request("team-review-org", "team-pr-review", pr_opt)
        .await
        .expect("couldn't create pr");

    let review_opt = PullReviewRequestOptions {
        reviewers: None,
        team_reviewers: Some(vec!["Owners".into()]),
    };
    api.repo_create_pull_review_requests("team-review-org", "team-pr-review", 1, review_opt)
        .await
        .expect("couldn't request review");

    let pr = api
        .repo_get_pull_request("team-review-org", "team-pr-review", 1)
        .await
        .expect("couldn't get pr");
    assert_eq!(pr.requested_reviewers, Some(vec![]));

    let team_name = api
        .org_list_teams("team-review-org")
        .all()
        .await
        .expect("failed to list teams")
        .pop()
        .and_then(|team| team.name);
    assert_eq!(
        pr.requested_reviewers_teams
            .and_then(|mut teams| teams.pop()?.name),
        team_name
    );
}

#[tokio::test]
async fn tag_protection() {
    let api = common::login();
    let git = Git::new("./test_repos/tag-protect");
    let _ = basic_repo(&api, &git, "tag-protect").await;

    let tag_protections = api
        .repo_list_tag_protection("TestingAdmin", "tag-protect")
        .await
        .expect("failed to list tag protections");
    assert!(tag_protections.is_empty());

    let protection_opt = CreateTagProtectionOption {
        name_pattern: Some("v*".into()),
        whitelist_teams: None,
        whitelist_usernames: Some(vec!["TestingAdmin".into()]),
    };
    let new_protection = api
        .repo_create_tag_protection("TestingAdmin", "tag-protect", protection_opt)
        .await
        .expect("failed to create tag protection");
    let pattern = new_protection
        .name_pattern
        .as_deref()
        .expect("protection does not have pattern");
    assert_eq!(pattern, "v*");
    let id = new_protection.id.expect("protection does not have id");

    let protection_get = api
        .repo_get_tag_protection("TestingAdmin", "tag-protect", id)
        .await
        .expect("failed to get tag protection");
    assert_eq!(new_protection, protection_get);

    let edit_opt = EditTagProtectionOption {
        name_pattern: Some("v*.*.*".into()),
        whitelist_teams: None,
        whitelist_usernames: Some(vec![]),
    };
    let edited = api
        .repo_edit_tag_protection("TestingAdmin", "tag-protect", id, edit_opt)
        .await
        .expect("failed to edit tag protection");
    let pattern = edited
        .name_pattern
        .as_deref()
        .expect("protection does not have pattern");
    assert_eq!(pattern, "v*.*.*");

    api.repo_delete_tag_protection("TestingAdmin", "tag-protect", id)
        .await
        .expect("failed to delete tag protection");
}

#[tokio::test]
async fn repo_vars() {
    let api = common::login();
    let git = Git::new("./test_repos/repo-vars");
    let _ = basic_repo(&api, &git, "repo-vars").await;

    let (_, var_list) = api
        .get_repo_variables_list("TestingAdmin", "repo-vars")
        .await
        .expect("failed to list repo vars");
    assert!(var_list.is_empty());

    let opt = CreateVariableOption {
        value: "false".into(),
    };
    api.create_repo_variable("TestingAdmin", "repo-vars", "very_cool", opt)
        .await
        .expect("failed to create repo var");

    let new_var = api
        .get_repo_variable("TestingAdmin", "repo-vars", "very_cool")
        .await
        .expect("failed to get repo var");
    assert_eq!(new_var.data.as_deref(), Some("false"));

    // wait, that's not right. you ARE very cool!
    // gotta fix that
    let opt = UpdateVariableOption {
        name: Some("extremely_cool".into()),
        value: "true".into(),
    };
    api.update_repo_variable("TestingAdmin", "repo-vars", "very_cool", opt)
        .await
        .expect("failed to update repo variable");

    let new_var = api
        .get_repo_variable("TestingAdmin", "repo-vars", "extremely_cool")
        .await
        .expect("failed to get repo var");
    assert_eq!(new_var.data.as_deref(), Some("true"));

    api.delete_repo_variable("TestingAdmin", "repo-vars", "extremely_cool")
        .await
        .expect("failed to delete repo var");
}

#[tokio::test]
async fn many_repos() {
    use futures::stream::StreamExt;
    let api = common::login();

    for i in 0..100 {
        let opts = CreateRepoOption {
            auto_init: None,
            default_branch: None,
            description: None,
            gitignores: None,
            issue_labels: None,
            license: None,
            name: format!("many-repos-{i}"),
            object_format_name: None,
            private: None,
            readme: None,
            template: None,
            trust_model: None,
        };
        api.create_current_user_repo(opts).await.unwrap();
    }

    let mut stream = api
        .user_current_list_repos(UserCurrentListReposQuery { order_by: None })
        .stream();
    while let Some(repo) = stream.next().await {
        let repo = repo.expect("failed to list repos");
        eprintln!("{}", repo.full_name.as_deref().unwrap_or("missing name"));
    }
}

#[tokio::test]
async fn combined_status_list() {
    let api = common::login();
    let git = Git::new("./test_repos/combined-status-list");
    let _ = basic_repo(&api, &git, "combined-status-list").await;
    tokio::time::sleep(std::time::Duration::from_secs(3)).await;
    let sha = api
        .repo_get_branch("TestingAdmin", "combined-status-list", "main")
        .await
        .expect("failed to get main branch")
        .commit
        .expect("main branch does not have commit data")
        .id
        .expect("commit did not have id");

    for i in 0..100 {
        let opts = CreateStatusOption {
            context: Some(format!("Status #{i}")),
            description: Some(format!("This is commit status #{i}")),
            state: Some(CommitStatusState::Success),
            target_url: None,
        };
        api.repo_create_status("TestingAdmin", "combined-status-list", &sha, opts)
            .await
            .expect("failed to create commit status");
    }

    let statuses = api
        .repo_get_combined_status_by_ref("TestingAdmin", "combined-status-list", &sha)
        .stream_pages()
        .map_ok(|page| page.statuses.expect("statuses missing from page"))
        .map_ok(|page| futures::stream::iter(page).map(Result::<_, eyre::Report>::Ok))
        .try_flatten()
        .try_collect::<Vec<_>>()
        .await
        .expect("failed to get combined status list");

    assert_eq!(statuses.len(), 100);
}

#[tokio::test]
async fn url_encoding_labels() {
    let api = common::login();
    let git = Git::new("./test_repos/url-encoding-labels");
    let _ = basic_repo(&api, &git, "url-encoding-labels").await;

    let opt = CreateLabelOption {
        color: "FFFFFF".into(),
        description: None,
        exclusive: None,
        is_archived: None,
        name: "Testing/Scoped".into(),
    };
    api.issue_create_label("TestingAdmin", "url-encoding-labels", opt)
        .await
        .unwrap();
    let opt = CreateIssueOption {
        assignee: None,
        assignees: None,
        body: None,
        closed: None,
        due_date: None,
        labels: None,
        milestone: None,
        r#ref: None,
        title: "Test Issue".into(),
    };
    let issue = api
        .issue_create_issue("TestingAdmin", "url-encoding-labels", opt)
        .await
        .unwrap();
    let index = issue.number.unwrap();
    let opt = IssueLabelsOption {
        labels: Some(vec!["Testing/Scoped".into()]),
        updated_at: None,
    };
    api.issue_add_label("TestingAdmin", "url-encoding-labels", index, opt)
        .await
        .unwrap();
    let opt = DeleteLabelsOption { updated_at: None };
    api.issue_remove_label(
        "TestingAdmin",
        "url-encoding-labels",
        index,
        "Testing/Scoped",
        opt,
    )
    .await
    .unwrap();
}
