'use strict'

const SQL = require('./../lib/core/lib/db/SQL')
const udaru = require('./../lib/core')
const db = require('./../lib/core/lib/db')
const config = require('../lib/config/build-all')()

function createOrganization (job, next) {
  const superOrganizationData = config.get('authorization.superUser.organization')

  udaru.organizations.create(superOrganizationData, { createOnly: true }, (error, result) => {
    if (error) return next(error)

    job.organization = result.organization
    next()
  })
}

function createUser (job, next) {
  const { organization } = job

  const superUserData = {
    id: config.get('authorization.superUser.id'),
    name: config.get('authorization.superUser.name'),
    organizationId: organization.id
  }

  udaru.users.create(superUserData, (error, user) => {
    if (error) return next(error)

    job.user = user
    next()
  })
}

function createPolicy (job, next) {
  const { organization } = job

  const superUserPolicy = config.get('authorization.superUser.defaultPolicy', { organizationId: organization.id })

  udaru.policies.create(superUserPolicy, (error, policy) => {
    if (error) return next(error)

    job.policy = policy
    next()
  })
}

function attachPolicy (job, next) {
  const { user, policy } = job

  const sqlQuery = SQL`INSERT INTO user_policies (user_id, policy_id) VALUES (${user.id}, ${policy.id})`
  db.query(sqlQuery, next)
}

const tasks = [
  createOrganization,
  createUser,
  createPolicy,
  attachPolicy
]
db.withTransaction(tasks, (error, x) => {
  if (error) {
    console.error(error)
    process.exit(1)
  }

  db.shutdown(() => {
    console.log('done')
  })
})

@@ -61,17 +61,22 @@
 )%0Aconst 
-u
+buildU
 daru = r
@@ -105,17 +105,22 @@
 )%0Aconst 
-d
+buildD
 b = requ
@@ -198,16 +198,179 @@
 -all')()
+%0Aconst buildConfig = require('../lib/config')%0A%0Aconst fullConfig = buildConfig(%7B%7D, config)%0Aconst db = buildDb(null, fullConfig)%0Aconst udaru = buildUdaru(fullConfig)
 %0A%0Afuncti
@@ -1659,16 +1659,17 @@
 olicy%0A%5D%0A
+%0A
 db.withT
@@ -1813,16 +1813,36 @@
 'done')%0A
+    process.exit(0)%0A
   %7D)%0A%7D)%0A

fix db init script