class Api::ContractTemplatesController < Api::ApiController
  include ProjectContext

  before_action :set_project, only: [:index]
  before_action :set_contract_template, only: [:show]

  def index
    render jsonapi: contract_templates, class: { "ContractTemplate": index_serializable }
  end

  def show
    handle_response(@contract_template)
  end

  def handle_response(contract_template, status = :ok)
    mapping = {
      "ContractTemplate": show_serializable,
      "ActiveStorage::Attachment".to_sym => ActiveStorage::SerializableAttachment,
    }

    render jsonapi: contract_template,
           status: status,
           class: mapping
  end

  def attributes_for_index
    [:name]
  end

  def index_serializable
    name = "contract_template"
    attributes_to_send = attributes_for_index
    Class.new(JSONAPI::Serializable::Resource) do
      type name

      attributes_to_send.each do |attr|
        attribute attr.to_sym
      end
    end
  end

  def show_serializable
    name = "contract_template"
    Class.new(JSONAPI::Serializable::Resource) do
      type name

      ContractTemplate.new.attributes.keys.each do |attr|
        attribute attr.to_sym
      end
    end
  end

  private

  def contract_templates
    date = Date.parse(params.fetch(:updated_since, Date.new.to_s))
    policy_scope(ContractTemplate.where(project_id: @project.id, updated_at: date..Float::INFINITY))
  end

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