require 'dotenv/rails-now'

if Rails.env.test? || System::Application.config.three_scale.core.fake_server
  require Rails.root.join('test/test_helpers/backend')
  TestHelpers::Backend::MockCore.mock_core!
end

master_name = ENV.fetch('MASTER_NAME', 'Master Account')
master_service = ENV.fetch('MASTER_SERVICE', 'Master Service')
master_plan = ENV.fetch('MASTER_PLAN', 'Master Plan')
master_domain = ENV.fetch('MASTER_DOMAIN', '').presence
master_access_code = ENV.fetch('MASTER_ACCESS_CODE', '')

master = Account.create!(name: master_name) do |account|
  account.subdomain = master_domain
  account.self_subdomain = master_domain
  account.master = true
  account.provider = true
  account.site_access_code = master_access_code
end

master.provider_account = master
master.save!

FieldsDefinition.create_defaults(master)

master_user = ENV.fetch('MASTER_USER', '').presence
master_password = ENV.fetch('MASTER_PASSWORD', '').presence

if master_user && master_password
  User.create!(username: master_user,
               password: master_password, password_confirmation: master_password) do |user|
    user.signup_type = 'minimal'
    user.account = master
    user.role = :admin
    user.activate!
  end
end


master_service = Service.create!(account: master, name: master_service)

application_plan = ApplicationPlan.create!(issuer: master_service, name: master_plan)
application_plan.create_contract_with! master

# Enable account_plans / service_plans and end_users plans for Master
%i(end_users account_plans service_plans).each do |setting|
  master.settings.send(setting).show!
end

###
#  Creating Provider Account
###

provider_name = ENV.fetch('PROVIDER_NAME', 'Provider Name')
provider_subdomain = ENV.fetch('TENANT_NAME', 'provider')
sample_data = ENV.fetch('SAMPLE_DATA', '1') != '0'

provider = Account.create!(name: provider_name) do |account|
  account.subdomain = provider_subdomain
  account.generate_domains
  account.provider_account = master
  account.provider = true
  account.sample_data = sample_data
end

# Master no longer has to be a provider
master.update_columns(provider: false)

###
#  Creating Provider User
###

user_login = ENV.fetch('USER_LOGIN', 'admin')
user_email = ENV.fetch('USER_EMAIL', "#{user_login}@#{provider.domain}")
user_password = ENV.fetch('USER_PASSWORD') { SecureRandom.base64(32) }

user = User.create!(username: user_login, password: user_password, password_confirmation: user_password) do |user|
  user.signup_type = :minimal
  user.account = provider
  user.role = :admin
  user.email = user_email
  user.activate!
  user.account.create_onboarding
end

###
#  Setting up APIcast authentication
###

apicast_access_token = user.access_tokens.create!(name: 'APIcast', scopes: %w(account_management), permission: 'ro') do |token|
  if (value = ENV['APICAST_ACCESS_TOKEN'].presence)
    token.value = value
  end
end.value

if (admin_access_token = ENV['ADMIN_ACCESS_TOKEN'])
  access_token = user.access_tokens.build(name: 'Administration', permission: 'rw')
  access_token.scopes = access_token.class.scopes.values
  access_token.value = admin_access_token
  access_token.save!
end

###
#  Creating 3scaleadmin user for provider
###

three_scale_admin = provider.users.build_with_fields
three_scale_admin.account = provider
three_scale_admin.role = :admin
three_scale_admin.signup_type = :minimal

three_scale_admin.attributes = {
  username: '3scaleadmin',
  email: "3scaleadmin+#{provider.self_domain}@3scale.net",
  first_name: '3scale',
  last_name: 'Admin'
}

three_scale_admin.save!
three_scale_admin.activate!

###
#  Creating Sample Data
###

SignupWorker.enqueue(provider)

###
#  Enabling Provider Switches
###

provider_plan = ENV.fetch('PROVIDER_PLAN', 'enterprise')
plan = ApplicationPlan.new(issuer: master_service, name: provider_plan)

provider.force_upgrade_to_provider_plan!(plan)

###
# Basic enabled/disabled switches
###

Settings.basic_enabled_switches.each do |name|
  provider.settings.public_send("show_#{name}")
end

Settings.basic_disabled_switches.each do |name|
  provider.settings.public_send("hide_#{name}")
end

puts '='*80
puts
puts 'Setup Completed'
puts
puts "Root Domain: #{Account::Domains::SUPERDOMAIN}"

if master_user && master_password
  puts
  puts "Master Domain: #{master.admin_domain}"
  puts "Master User Login: #{master_user}"
  puts "Master User Password: #{master_password}"
  if master_access_code.present?
    puts "Master Access Code: #{master_access_code}"
  end
  puts
end
puts "Provider Admin Domain: #{provider.admin_domain}"
puts "Provider Portal Domain: #{provider.domain}"
puts "Provider User Login: #{user_login}"
puts "Provider User Password: #{user_password}"
puts "APIcast Access Token: #{apicast_access_token}"
if admin_access_token
  puts "Admin Access Token: #{admin_access_token}"
end
puts
puts '='*80
