# frozen_string_literal: true

class ContractTemplatesController < ApplicationController
  include ProjectContext

  layout 'project'

  before_action :set_project, except: [:destroy]
  before_action :set_contract_template, only: [:destroy]

  def index
    @contract_templates = contract_templates.non_archived.order_by_name.paginate(page: params[:page])
  end

  def new
    @contract_template = build_contract_template
  end

  def create
    @contract_template = build_contract_template(contract_template_params)
    if params[:commit] == 'preview'
      ctp = ContractTemplatePreview.new(@contract_template)
      releasable_instance = ctp.build_releasable
      contract = Contract.new releasable_instance, true
      send_file contract.to_pdf, download_attributes
    elsif @contract_template.save
      redirect_to [@project, :contract_templates], notice: t('.notice')
    else
      @release_type = contract_template_params[:release_type]
      render :new
    end
  end

  def destroy
    @contract_template.archive
    redirect_to [@contract_template.project, :contract_templates], alert: t('.archived_notice')
  end

  private

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

  def contract_templates
    if @project
      policy_scope(@project.contract_templates)
    else
      policy_scope(ContractTemplate)
    end
  end

  def build_contract_template(attrs = {})
    authorize contract_templates.build(attrs)
  end

  def contract_template_params
    params
      .require(:contract_template)
      .permit(:name, :release_type, :body, :guardian_clause, :fee,
              :applicable_medium_id, :applicable_medium_text,
              :territory_id, :territory_text,
              :term_id, :term_text,
              :restriction_id, :restriction_text,
              :question_1_text, :question_2_text, 
              :question_3_text, :question_4_text, 
              :question_5_text, :question_6_text, 
              :question_7_text, :question_8_text, 
              :question_9_text, :question_10_text)
  end

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