from gitlab import Gitlab
from gitlab.v4.objects.issues import ProjectIssue

from csirtmu.beta_temporal.config import GitlabConfig


class GitlabClient:
    def __init__(self, gitlab: Gitlab, config: GitlabConfig) -> None:
        self.gitlab = gitlab
        self.config = config

    def get_open_issues(self) -> list[ProjectIssue]:
        return self.gitlab.projects.get(self.config.project_id).issues.list(
            state="opened",
            author_id=self.config.service_account_id,
            get_all=True,
        )

    def create_issue(self, title: str, description: str) -> int:
        new_issue = self.gitlab.projects.get(self.config.project_id).issues.create(
            data={
                "title": title,
                "description": description,
                "assignee_ids": self.config.assignee_ids,
                "labels": self.config.labels,
            }
        )
        return new_issue.iid

    def comment_issue(self, issue_id: int, comment: str) -> int:
        note = (
            self.gitlab.projects.get(self.config.project_id)
            .issues.get(issue_id)
            .notes.create(
                data={"body": comment},
            )
        )
        return note.id
