module PayoutEntities
  class ContractDetails < PayoutEntities::Base
    attributes :invitation_id, :contract_url, :contract_start_date,
               :contract_end_date, :contract_auto_renew,
               :contract_auto_renew_notice, :contract_renewal_term

    self.primary_attribute = :invitation_id

    validates :contract_url, :contract_start_date, :contract_end_date,
              :contract_auto_renew_notice, :contract_renewal_term, presence: true

    CONTRACT_BLANK_DATE = "0001-01-01T00:00:00Z"

    def self.find(invitation_id, options)
      response = get "/payout/invite/contract/#{invitation_id}", headers: ldap_headers(options)

      return {} unless response.success?

      details = transform_dates(response.body)

      result = details.values.any? {|v| v.present?} ? details : {}
      result["invitation_id"] = invitation_id
      from_attributes result
    end

    def save(invitation_id, options)
      return false unless valid?

      response = post "/payout/invite/contract/#{invitation_id}", body: save_params.to_json, headers: PayoutEntity.ldap_headers(options)
      self.errors = response.body unless response.success?
      response.success?
    end

    protected

    def self.transform_dates(details)
      start_date = (details["contract_start_date"].present? && details["contract_start_date"] != CONTRACT_BLANK_DATE) ? details["contract_start_date"].to_date : nil
      end_date = (details["contract_end_date"].present? && details["contract_end_date"] != CONTRACT_BLANK_DATE) ? details["contract_end_date"].to_date : nil

      details["contract_start_date"] = start_date
      details["contract_end_date"] = end_date

      details
    end

    def save_params
      {
        contract_url: contract_url,
        contract_start_date: contract_start_date.to_datetime,
        contract_end_date: contract_end_date.to_datetime,
        contract_auto_renew: self.class.booleanize(contract_auto_renew),
        contract_auto_renew_notice: contract_auto_renew_notice,
        contract_renewal_term: contract_renewal_term
      }
    end
  end
end
