use crate::{
    domain::{EditIssue, IssueDraft},
    models,
};

pub(super) fn create_issue_option(draft: IssueDraft) -> models::CreateIssueOption {
    models::CreateIssueOption {
        body: Some(draft.body),
        closed: Some(draft.closed),
        due_date: draft.due_date,
        labels: Some(draft.label_ids),
        milestone: draft.milestone_id,
        ..models::CreateIssueOption::new(draft.title)
    }
}

pub(super) fn edit_issue_draft(draft: IssueDraft) -> EditIssue {
    EditIssue {
        option: models::EditIssueOption {
            body: Some(draft.body),
            due_date: draft.due_date.clone(),
            milestone: Some(draft.milestone_id.unwrap_or_default()),
            state: Some(if draft.closed { "closed" } else { "open" }.into()),
            title: Some(draft.title),
            unset_due_date: draft.due_date.is_none().then_some(true),
            ..models::EditIssueOption::new()
        },
        replace_labels: Some(draft.label_ids),
        add_labels: Vec::new(),
        remove_labels: Vec::new(),
        add_assignees: Vec::new(),
        milestone_name: None,
    }
}

pub(super) fn label_option(labels: &[i64]) -> models::IssueLabelsOption {
    models::IssueLabelsOption {
        labels: Some(
            labels
                .iter()
                .copied()
                .map(serde_json::Value::from)
                .collect(),
        ),
    }
}

pub(super) fn comment_belongs_to_issue(comment: &models::Comment, number: i64) -> bool {
    comment
        .issue_url
        .as_deref()
        .map(|url| url.trim_end_matches('/'))
        .and_then(|url| url.rsplit('/').next())
        .and_then(|index| index.parse().ok())
        == Some(number)
}
