class Api::V1::Projects::WebhooksController < Api::V1::BaseController 
  before_action :require_manager_above
  before_action :find_webhook, only: [:show, :update, :destroy, :tests, :hooktasks]

  def index 
    # @result_object = Api::V1::Projects::Webhooks::ListService.call(@project, current_user&.gitea_token)
    @webhooks = @project.webhooks
    @webhooks = @webhooks.where(type: params[:type]) if params[:type].present?
    @webhooks = kaminari_paginate(@webhooks)
  end

  def create 
    return render_error("webhooks数量已到上限！请删除暂不使用的webhooks以进行添加操作") if @project.webhooks.size > 49
    @result_object = Api::V1::Projects::Webhooks::CreateService.call(@project, create_webhook_params, current_user&.gitea_token)
  end

  def show 
    @result_object = Api::V1::Projects::Webhooks::GetService.call(@project, params[:id], current_user&.gitea_token)
  end

  def update 
    @result_object = Api::V1::Projects::Webhooks::UpdateService.call(@project, params[:id], webhook_params, current_user&.gitea_token)
  end

  def destroy 
    @result_object = Api::V1::Projects::Webhooks::DeleteService.call(@project, params[:id], current_user&.gitea_token)
    if @result_object
      return render_ok 
    else
      return render_error('删除失败!') 
    end
  end

  def tests 
    @result_object = Api::V1::Projects::Webhooks::TestsService.call(@project, params[:id], current_user&.gitea_token)
    if @result_object
      return render_ok 
    else
      return render_error('推送失败!') 
    end
  end

  def hooktasks 
    @hooktasks = @webhook.tasks.where(is_delivered: true).order("delivered desc")
    @hooktasks = kaminari_paginate(@hooktasks)
  end

  private 
  def create_webhook_params 
    params.require(:webhook).permit(:active, :branch_filter, :http_method, :url, :content_type, :secret, :type, events: [])
  end

  def webhook_params 
    params.require(:webhook).permit(:active, :branch_filter, :http_method, :url, :content_type, :secret, events: [])
  end

  def find_webhook 
    @webhook = Gitea::Webhook.find_by_id(params[:id])
    return render_not_found unless @webhook.present?
  end
end