logger = (require 'logging').default '/user/login'

# session storage (volatile data)
session = (require '../../session')
# fftcg.db (persistent data)
fftcgdb = (require '../../db')

module.exports =
  url: '/user/login'
  method: 'POST'
  schema: (require './user.schema')

  handler: (request, reply) ->
    new Promise (resolve) ->
      session.check request.body.session ? ""
      .then (user) ->
        # active session found
        logger.debug "OK '#{user.login}' resumed session '#{request.body.session}'"
        resolve request.body.session

      .catch ->
        fftcgdb.login request.body.login, request.body.password
        .then (user) ->
          # login successful: start new session
          logger.info "OK '#{request.body.login}'"
          session.start user
          .then (cookie_data) ->
            resolve cookie_data

        .catch (err) ->
          # login failed
          logger.info "FAIL '#{request.body.login}: #{err}'"
          reply.send
            success: false
            message: err

    .then (cookie_data) ->
      # login or resume successful
      reply.send
        success: true
        message: JSON.stringify cookie_data
