#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")/.."
# shellcheck disable=SC1091
source scripts/lib-compose.sh

email="${CHATWOOT_ADMIN_EMAIL:-admin@localhost}"
pass="${CHATWOOT_ADMIN_PASSWORD:-ChangeMe123!}"

compose exec -T rails bundle exec rails runner "
if User.exists?(email: '${email}')
  puts 'User already exists: ${email}'
else
  u = User.create!(
    name: 'Admin',
    email: '${email}',
    password: '${pass}',
    password_confirmation: '${pass}',
    type: 'SuperAdmin'
  )
  u.update!(confirmed_at: Time.current)
  acc = Account.create!(name: 'Support')
  AccountUser.create!(account: acc, user: u, role: :administrator)
  ch = Channel::WebWidget.create!(account: acc, website_url: '${CHATWOOT_FRONTEND_URL:-http://localhost:3010}')
  Inbox.create!(account: acc, channel: ch, name: 'Website')
  puts 'Created admin ${email} / password from CHATWOOT_ADMIN_PASSWORD in .env'
  puts 'Website token: ' + ch.website_token
  ::Redis::Alfred.delete(::Redis::Alfred::CHATWOOT_INSTALLATION_ONBOARDING)
end
"
