import { Router } from 'express'
import { requireCompanyAuth } from '../../middleware/requireCompanyAuth'
import { requireTenant } from '../../middleware/requireTenant'
import { requireSubscription } from '../../middleware/requireSubscription'
import { requireRole } from '../../middleware/requireRole'
import { parseBody, parseParams } from '../../http/validate'
import { ok, created } from '../../http/respond'
import * as service from './team.service'
import { inviteSchema, roleSchema, idParamSchema } from './team.schemas'

const router = Router()

router.use(requireCompanyAuth, requireTenant, requireSubscription)

router.get('/', async (req, res, next) => {
  try {
    ok(res, await service.getMembers(req.companyId))
  } catch (err) { next(err) }
})

router.get('/stats', async (req, res, next) => {
  try {
    ok(res, await service.getMemberStats(req.companyId))
  } catch (err) { next(err) }
})

router.post('/invite', requireRole('OWNER'), async (req, res, next) => {
  try {
    const body = parseBody(inviteSchema, req)
    created(res, { data: await service.inviteEmployee(req.companyId, req.employee.id, body) })
  } catch (err) { next(err) }
})

router.patch('/:id/role', requireRole('OWNER'), async (req, res, next) => {
  try {
    const { id } = parseParams(idParamSchema, req)
    const { role } = parseBody(roleSchema, req)
    ok(res, await service.updateEmployeeRole(req.companyId, req.employee.id, req.employee.role, id, { role }))
  } catch (err) { next(err) }
})

router.post('/:id/deactivate', requireRole('OWNER'), async (req, res, next) => {
  try {
    const { id } = parseParams(idParamSchema, req)
    ok(res, await service.deactivateEmployee(req.companyId, req.employee.role, id))
  } catch (err) { next(err) }
})

router.post('/:id/reactivate', requireRole('OWNER'), async (req, res, next) => {
  try {
    const { id } = parseParams(idParamSchema, req)
    ok(res, await service.reactivateEmployee(req.companyId, req.employee.role, id))
  } catch (err) { next(err) }
})

router.delete('/:id', requireRole('OWNER'), async (req, res, next) => {
  try {
    const { id } = parseParams(idParamSchema, req)
    ok(res, await service.removeEmployee(req.companyId, req.employee.role, id))
  } catch (err) { next(err) }
})

export default router
