class Public::AmendmentsController < Public::BaseController
  skip_after_action :verify_authorized, :verify_policy_scoped
  before_action :set_account, :set_project, :set_contract_template, :set_release

  def new
    if @release.amendment_signed?
      render :create, locals: { already_signed: true }
    end
  end

  def create
    if @release.amendment_signed?
      render :create, locals: { already_signed: true }
      return
    end

    @release.attributes = amendment_params

    render :new unless @release.save(context: :amendment)
  end

  private

  def amendment_params
    params.require(releasable_param.name).permit(:amendment_signer_name, :amendment_signature_base64)
  end

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

  def set_release
    @release = @contract_template.releases.find(releasable_param.id)
  end

  def set_contract_template
    @contract_template = @project.contract_templates.find(params[:contract_template_id])
  end

  def set_project
    @project = @account.projects.find(params[:project_id])
  end

  def set_account
    @account = Account.find_by(slug: params[:account_id])
  end
end