logger = (require 'logging').default '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_id = request.cookies.session ? ''
      session.check session_id
      .then (user) ->
        # active session found
        logger.debug "OK '#{user.login}' resumed session '#{session_id}'"
        resolve user

      .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 (session_id) ->
            reply.setCookie 'session', session_id
            resolve user

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

    .then (user) ->
      # tell about the user who logged in
      reply.send
        success: true
        user: user
