import { Router } from 'express'
import { requireCompanyAuth } from '../../middleware/requireCompanyAuth'
import { parseBody } from '../../http/validate'
import { ok } from '../../http/respond'
import {
  employeeForgotPasswordSchema,
  employeeLanguageSchema,
  employeeLoginSchema,
  employeeResetPasswordSchema,
} from './auth.employee.schemas'
import * as service from './auth.employee.service'

const router = Router()

router.get('/me', requireCompanyAuth, async (req, res, next) => {
  try {
    ok(res, await service.getMe(req.employee.id))
  } catch (err) { next(err) }
})

router.post('/login', async (req, res, next) => {
  try {
    const body = parseBody(employeeLoginSchema, req)
    ok(res, await service.login(body))
  } catch (err) { next(err) }
})

router.post('/forgot-password', async (req, res, next) => {
  try {
    const { email } = parseBody(employeeForgotPasswordSchema, req)
    ok(res, await service.forgotPassword(email))
  } catch (err) { next(err) }
})

router.patch('/me/language', requireCompanyAuth, async (req, res, next) => {
  try {
    const { language } = parseBody(employeeLanguageSchema, req)
    ok(res, await service.updateLanguage(req.employee.id, language))
  } catch (err) { next(err) }
})

router.post('/reset-password', async (req, res, next) => {
  try {
    const { token, password } = parseBody(employeeResetPasswordSchema, req)
    ok(res, await service.resetPassword(token, password))
  } catch (err) { next(err) }
})

export default router
