class Api::V1::Users::HomeTopSettings::DeleteService < ApplicationService

  include ActiveModel::Model 

  attr_reader :user, :top_type, :top_id 
  attr_accessor :home_top_setting, :home_top

  validates :user, :top_type, :top_id, presence: true
  validates :top_type, inclusion: {in: %w(Organization Project), message: '请输入正确的TopType'}

  def initialize(user, params)
    @user = user 
    @top_type = params[:top_type]
    @top_id = params[:top_id]
  end

  def call 
    raise Error, errors.full_messages.join(",") unless valid? 
    raise Error, "置顶对象不存在！" unless find_home_top
    raise Error, "置顶对象未置顶！" unless check_home_top_setting

    begin
      @home_top_setting = HomeTopSetting.find_by(user:user, top: @home_top)
      @home_top_setting.destroy!

      return true
    rescue 
      raise Error, "服务器错误，请联系系统管理员！"
      
    end
  end

  def find_home_top
    @home_top = @top_type.constantize.find_by_id(@top_id).presence
  end

  def check_home_top_setting
    HomeTopSetting.exists?(user: @user, top: @home_top)
  end
end