import { Router } from 'express'
import { requireCompanyAuth } from '../../middleware/requireCompanyAuth'
import { parseBody } from '../../http/validate'
import { ok } from '../../http/respond'
import { setSessionCookie, clearSessionCookie } from '../../security/sessionCookies'
import { getEmployeeMenu } from '../menu/menu.service'
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.get('/menu', requireCompanyAuth, async (req, res, next) => {
  try {
    ok(res, await getEmployeeMenu(req.employee.id))
  } catch (err) { next(err) }
})

router.post('/login', async (req, res, next) => {
  try {
    const body = parseBody(employeeLoginSchema, req)
    const result = await service.login(body)
    if ('token' in result) setSessionCookie(res, 'employee', result.token, 8 * 60 * 60 * 1000)
    ok(res, result)
  } catch (err) { next(err) }
})

router.post('/logout', (_req, res) => {
  clearSessionCookie(res, 'employee')
  ok(res, { success: true })
})

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) }
})

router.post('/verify-email', async (req, res, next) => {
  try {
    const { token } = parseBody(employeeResetPasswordSchema.pick({ token: true }), req)
    ok(res, await service.verifyEmail(token))
  } catch (err) { next(err) }
})

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

export default router
