# == Schema Information
#
# Table name: project_actions
#
#  id          :integer          not null, primary key
#  project_id  :integer
#  type        :string(255)
#  user_id     :integer
#  event_extra :text(65535)
#  created_at  :datetime         not null
#  updated_at  :datetime         not null
#
# Indexes
#
#  index_project_actions_on_project_id  (project_id)
#


class ProjectActions::PullRequestEvent < ProjectAction
  def self.build(project, user, pull_request, action)
    project_action = new(project: project, user: user)
    gitea_pull_request = Gitea::PullRequest::FilesService.call(project.owner.login, project.identifier, pull_request.gitea_number, project&.owner&.gitea_token)
    project_action.event_extra = {
      action: action,
      pull_id: pull_request.id,
      pull_number: pull_request.gitea_number,
      title: pull_request.title,
      body: pull_request.body,
      git_diff: gitea_pull_request,
      additions: gitea_pull_request['TotalAddition'],
      deletions: gitea_pull_request['TotalDeletion'],
      changed_files: gitea_pull_request['NumFiles'],
      merged: pull_request.status == 1,
      base_ref: pull_request.base,
      head_repo_id: pull_request.is_original ? pull_request.fork_project_id : pull_request.project_id,
      head_repo_name: pull_request.project&.identifier,
      head_ref: pull_request.head
    }
    project_action.save!
  end
end
