require 'will_paginate/array'
class ReleaseTemplateImportsController < ApplicationController
  include ProjectContext

  layout "project"

  before_action :set_project

  def new
    authorize ContractTemplate, :new?

    templates = []
    filtered_contract_templates.each do |contract_template|
      next if contract_template.duplicated? ||
              contract_template.archived? ||
              contract_template.project == @project

      already_imported = contract_template.duplicates.non_archived.pluck(:project_id).include?(@project.id)
      templates << OpenStruct.new(template: contract_template, already_imported?: already_imported)
    end

    # Already imported templates to the end of list
    templates.sort_by! { |t| t.already_imported? ? 1 : 0 }

    @importable_templates = templates.paginate(page: params[:page])
  end

  def create
    authorize ContractTemplate, :create?

    # Authorize each of the contract templates separately
    ContractTemplate.where(id: params[:template_ids]).each { |ct| authorize ct, :import? }
    if @project.import_contract_templates(params[:template_ids])
      redirect_to project_contract_templates_path(@project), notice: t(".imported")
    else
      redirect_to project_contract_templates_path(@project), alert: t(".error")
    end
  end

private

  def filtered_contract_templates
    if params[:query].present?
      search_results = ContractTemplate.search(params[:query])
      policy_scope(ContractTemplate).where(id: search_results.select(:id))
    else
      policy_scope(ContractTemplate)
    end
  end
end