# frozen_string_literal: true

class ContractTemplates::BlankContractsController < ApplicationController
  before_action :set_contract_template

  def show
    send_file contract.to_pdf, download_attributes
  end

  def new
    authorize BlankContract
    render 'blank_contracts/new'
  end

  def create
    if number_of_copies_valid?
      send_file contract.to_pdf, download_attributes
    else
      authorize BlankContract
      redirect_back fallback_location: [:new, @contract_template, :blank_contracts], notice: t('.number_of_copies_invalid_notice')
    end
  end

  private

  def number_of_copies_valid?
    number_of_copies = params[:number_of_copies].to_i
    number_of_copies.positive?
  rescue StandardError
    false
  end

  def contract_templates
    policy_scope(ContractTemplate)
  end

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

  def releasable
    create_releasable_instance
  end

  def create_releasable_instance
    template_release_type = @contract_template[:release_type]
    releasable = "#{template_release_type}_release".classify.safe_constantize.new
    releasable.contract_template = @contract_template
    releasable.project_id = @contract_template.project_id
    releasable
  end

  def contract
    authorize BlankContract.new(releasable, params[:number_of_copies])
  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
end
