#The MIT License (MIT)
#
#Copyright (c) 2016 - 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

class Qbo < ActiveRecord::Base
    
  include QuickbooksOauth
  include Redmine::I18n

  validate :single_record_only, on: :create

  # Returns the last sync time formatted for display. If no sync has occurred, returns a default message.
  def self.last_sync
    qbo = QboConnectionService.current!
    format_time(qbo.last_sync)
  rescue
    return I18n.t(:label_qbo_never_synced)
  end

  def self.oauth2_access_token_expires_at
    QboConnectionService.current!.oauth2_access_token_expires_at
  rescue
    return I18n.t(:label_qbo_never_synced)
  end

  def self.oauth2_refresh_token_expires_at
    QboConnectionService.current!.oauth2_refresh_token_expires_at
  rescue
    return I18n.t(:label_qbo_never_synced)
  end
  
  # Updates last sync time stamp
  def self.update_time_stamp
    date = DateTime.now
    log "Updating QBO timestamp to #{date}"
    qbo = QboConnectionService.current!
    qbo.last_sync = date
    qbo.save
  end
  
  private

  # Logs a message with a QBO-specific prefix for easier identification in the logs.
  def self.log(msg)
    logger.info "[QBO] #{msg}"
  end

  # Validates that only one QBO connection record exists in the database. Adds an error if a record already exists.
  def single_record_only
    errors.add(:base, "Only one QBO connection allowed") if Qbo.exists?
  end

end
