class Projects::ProjectInviteLinksController < Projects::BaseController
  before_action :require_manager!, except: [:show_link, :redirect_link]
  before_action :require_login

  def current_link
    role = params[:role]
    is_apply = params[:is_apply]
    return render_error('请输入正确的参数！') unless role.present? && is_apply.present?
    @project_invite_link = ProjectInviteLink.find_by(user_id: current_user.id, project_id: @project.id, role: role, is_apply: is_apply)
    @project_invite_link = ProjectInviteLink.build!(@project, current_user, role, is_apply) unless @project_invite_link.present?
  end

  def generate_link
    ActiveRecord::Base.transaction do
      params_data = link_params.merge({user_id: current_user.id, project_id: @project.id})
      Projects::ProjectInviteLinks::CreateForm.new(params_data).validate!
      @project_invite_link = ProjectInviteLink.build!(project, user, params_data[:role], params_data[:is_apply])
    end
  rescue Exception => e
    uid_logger_error(e.message)
    tip_exception(e.message)
  end

  def show_link 
    @project_invite_link = ProjectInviteLink.find_by(sign: params[:invite_sign])
    return render_not_found unless @project_invite_link.present?
  end

  def redirect_link 
    Projects::LinkJoinService.call(current_user, @project, params[:invite_sign])
    render_ok
  rescue Exception => e
    uid_logger_error(e.message)
    normal_status(-1, e.message)
  end


  private 
  def link_params 
    params.require(:project_invite_link).permit(:role, :is_apply)
  end
end
