class Api::V1::Projects::Contents::BatchCreateService < ApplicationService 
  include ActiveModel::Model 

  attr_reader :project, :owner, :repo, :token 
  attr_reader :files, :author_email, :author_name, :author_timeunix, :branch, :committer_email, :committer_name, :committer_timeunix, :message, :new_branch
  attr_accessor :gitea_data 

  validates :author_email, :committer_email, presence: true, format: { with: CustomRegexp::EMAIL }
  validates :author_name, :committer_name, presence: true, format: { with: /\A(?!_)(?!.*?_$)[a-zA-Z0-9_-]{4,15}\z/ }
  validates :author_timeunix, :committer_timeunix, presence: true 
  validates :branch, presence: true 
  validates :message, presence: true


  def initialize(project, params, token=nil)
    @project = project 
    @owner = project&.owner.login 
    @repo = project&.identifier
    @token = token 
    @files = params[:files]
    @author_email = params[:author_email]
    @author_name = params[:author_name]
    @author_timeunix = params[:author_timeunix] || Time.now.to_i
    @branch = params[:branch]
    @committer_email = params[:committer_email]
    @committer_name = params[:committer_name]
    @committer_timeunix = params[:committer_timeunix] || Time.now.to_i
    @message = params[:message]
    @new_branch = params[:new_branch]
  end

  def call 
    raise Error, '请输入正确的文件参数Files' unless valid_files?
    raise Error, errors.full_messages.join(", ") unless valid? 
    check_branch_exist
    excute_data_to_gitea 

    gitea_data 
  end

  private 
  def request_params 
    {
      access_token: token
    }
  end
  
  def request_body 
    {
      files: files,
      header: {
        author: {
          email: author_email,
          name: author_name
        },
        committer: {
          email: committer_email,
          name: committer_name
        },
        dates: {
          author: Time.at(author_timeunix.to_i),
          committer: Time.at(committer_timeunix.to_i)
        },
        message: message,
        branch: branch,
        new_branch: new_branch,
        signoff: false
      }
    }
  end

  def valid_files?
    return false unless files.is_a?(Array) && !files.blank?
    files.each do |file|
      return false unless file.has_key?(:action_type) && file.has_key?(:content) && file.has_key?(:encoding) && file.has_key?(:file_path)
    end
  end

  def excute_data_to_gitea
    puts request_body.to_json
    @gitea_data = $gitea_hat_client.post_repos_contents_batch_by_owner_repo(owner, repo, {body: request_body.to_json, query: request_params}) rescue nil 
    raise Error, '提交文件失败！' unless @gitea_data.is_a?(Hash)
  end

  def check_branch_exist 
    result = $gitea_hat_client.get_repos_branch_name_set_by_owner_repo(owner, repo, {query: request_params} ) rescue nil 
    raise Error, '查询分支名称失败！' unless result.is_a?(Array)
    raise Error, '分支不存在！' unless result.include?(branch)
    raise Error, '分支已存在！' if result.include?(new_branch) && !new_branch.nil?
  end

end