# frozen_string_literal: true

class ContractTemplates::DuplicatesController < ApplicationController
  before_action :set_contract_template

  def create
    authorize(ContractTemplate)
    new_contract_template = @contract_template.dup
    new_contract_template.name = I18n.t('contract_templates.duplicate.name_prefix', template_name: @contract_template.name)

    # Duplicate rich text fields

    new_contract_template.body = @contract_template.body
    new_contract_template.guardian_clause = @contract_template.guardian_clause
    new_contract_template.signature_legal_text = @contract_template.signature_legal_text

    if new_contract_template.save
      redirect_to [:edit, new_contract_template]
    else
      redirect_to [@contract_template.project, :contract_templates], alert: t('.error')
    end
  end

  private

  def contract_templates
    policy_scope(ContractTemplate)
  end

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