class ContractsController < ApplicationController
  def show
    respond_to do |format|
      format.pdf { send_contract_pdf }

      if Rails.env.development?
        format.html { render_sample_html }
      end
    end
  end

  private

  def releases
    if @project
      policy_scope(@project.public_send(releasable_param.name.pluralize))
    else
      policy_scope(releasable_param.type)
    end
  end

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

  def releasable
    authorize releases.find(releasable_param.id)
  end

  def contract
    authorize Contract.new(releasable)
  end

  def download_attributes
    {
      disposition: "inline",
      filename: contract.filename,
      type: "application/pdf",
    }
  end

  def render_sample_html
    # NOTE: For development purposes, this contract renders with the current locale, not the locale of the release itself
    render contract.render_attributes
  end

  def send_contract_pdf
    # Native release contracts must be generated on-the-fly; non-native releases have a contract attachment
    if releasable.native?
      send_file contract.to_pdf, download_attributes
    else
      redirect_to releasable.contract.service_url
    end
  end
end
