class ApprovalsController < ApplicationController
  before_action :set_releasable
  before_action :set_project

  layout "project"

  def create
    @releasable.approve_by(current_user)
    @releasable.approved_by_user_signature.attach(approved_by_user_signature_params) if signature_data.present?

    if @releasable.save(context: :approval)
      redirect_to [@project, "#{@releasable_param.name.pluralize}"], notice: t('.release_approved', release_type: @releasable.model_name.human)
    else
      render :new
    end
  end

  private

  def releasable_param
    @releasable_param ||= ReleasableParam.new(params.to_unsafe_h)
  end

  def set_releasable
    @releasable = authorize policy_scope(releasable_param.type).find(releasable_param.id)
  end

  def set_project
    @project = @releasable.project
  end

  def releasable_params
    params.require(releasable_param.name).permit(approved_by_user_signature: :data)
  end

  def signature_data
    releasable_params.dig(:approved_by_user_signature, :data)
  end

  def approved_by_user_signature_params
    {
      data: signature_data,
      filename: "approved_by_user_signature.png",
      content_type: "image/png",
      identify: false,
    }
  end
end
