# frozen_string_literal: true

# 设置相关路由
module SettingRoutes
  def self.registered(app)
    # API: 测试云端连接
    app.post '/api/test-connection' do
      content_type :json

      api_token = params[:api_token]&.strip
      cloud_url = params[:cloud_url]&.strip

      if api_token.nil? || api_token.empty?
        return {
          success: false,
          message: 'API 令牌不能为空'
        }.to_json
      end

      if cloud_url.nil? || cloud_url.empty?
        return {
          success: false,
          message: '云端地址不能为空'
        }.to_json
      end

      result = CloudClient.test_connection(api_token, cloud_url)
      result.to_json
    end
    # 设置页面 - 配置API令牌
    app.get '/setup' do
      @active_page = 'config'
      @api_token = SETTINGS.get(:api_token) || ''
      @cloud_url = SETTINGS.get(:cloud_url) || ''
      erb :config, layout: true
    end

    # 保存API令牌
    app.post '/setup' do
      api_token = params[:api_token]&.strip
      cloud_url = params[:cloud_url]&.strip

      if api_token.nil? || api_token.empty?
        redirect '/setup?error=' + URI.encode_www_form_component('API令牌不能为空')
      else
        # 测试API令牌
        if CloudClient.test_token(api_token, cloud_url)
          SETTINGS.save_api_token(api_token)
          SETTINGS.save_cloud_url(cloud_url)
          session[:api_token] = api_token
          redirect '/'
        else
          redirect '/setup?error=' + URI.encode_www_form_component('API令牌无效或无法连接到云端')
        end
      end
    end

    # 配置页面 - 修改已有的API令牌
    app.get '/config' do
      @active_page = 'config'
      @api_token = SETTINGS.get(:api_token) || ''
      @cloud_url = SETTINGS.get(:cloud_url) || ''
      erb :config, layout: true
    end

    # 保存配置
    app.post '/config' do
      api_token = params[:api_token]&.strip
      cloud_url = params[:cloud_url]&.strip

      if api_token.nil? || api_token.empty?
        redirect '/config?error=' + URI.encode_www_form_component('API令牌不能为空')
      else
        # 测试API令牌
        if CloudClient.test_token(api_token, cloud_url)
          SETTINGS.save_api_token(api_token)
          SETTINGS.save_cloud_url(cloud_url)
          session[:api_token] = api_token
          redirect '/config?notice=' + URI.encode_www_form_component('配置已更新！')
        else
          redirect '/config?error=' + URI.encode_www_form_component('API令牌无效或无法连接到云端')
        end
      end
    end

    # 重置配置
    app.post '/reset-config' do
      SETTINGS.clear_auth
      session[:api_token] = nil
      redirect '/setup'
    end
  end
end