import { Router } from 'express'
import { z } from 'zod'
import { listEmployees, inviteEmployee, updateEmployeeRole, deactivateEmployee, reactivateEmployee, removeEmployee } from '../services/teamService'
import { requireCompanyAuth } from '../middleware/requireCompanyAuth'
import { requireTenant } from '../middleware/requireTenant'
import { requireSubscription } from '../middleware/requireSubscription'
import { requireRole } from '../middleware/requireRole'

const router = Router()
router.use(requireCompanyAuth, requireTenant, requireSubscription)

const inviteSchema = z.object({
  firstName: z.string().min(1).max(64),
  lastName:  z.string().min(1).max(64),
  email:     z.string().email(),
  role:      z.enum(['MANAGER', 'AGENT']),
})

router.get('/', async (req, res, next) => {
  try { res.json({ data: await listEmployees(req.companyId) }) } catch (err) { next(err) }
})

router.get('/stats', async (req, res, next) => {
  try {
    const members = await listEmployees(req.companyId)
    res.json({ data: { total: members.length, active: members.filter((m) => m.isActive && m.invitationStatus === 'accepted').length, pending: members.filter((m) => m.invitationStatus === 'pending').length, inactive: members.filter((m) => !m.isActive && m.invitationStatus === 'accepted').length } })
  } catch (err) { next(err) }
})

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

router.patch('/:id/role', requireRole('OWNER'), async (req, res, next) => {
  try {
    const { role } = z.object({ role: z.enum(['MANAGER', 'AGENT']) }).parse(req.body)
    const memberId = req.params.id!
    res.json({ data: await updateEmployeeRole(req.companyId!, req.employee!.id, req.employee!.role, memberId, { role }) })
  } catch (err) { next(err) }
})

router.post('/:id/deactivate', requireRole('OWNER'), async (req, res, next) => {
  try {
    const memberId = req.params.id!
    res.json({ data: await deactivateEmployee(req.companyId!, req.employee!.role, memberId) })
  } catch (err) { next(err) }
})

router.post('/:id/reactivate', requireRole('OWNER'), async (req, res, next) => {
  try {
    const memberId = req.params.id!
    res.json({ data: await reactivateEmployee(req.companyId!, req.employee!.role, memberId) })
  } catch (err) { next(err) }
})

router.delete('/:id', requireRole('OWNER'), async (req, res, next) => {
  try {
    const memberId = req.params.id!
    res.json({ data: await removeEmployee(req.companyId!, req.employee!.role, memberId) })
  } catch (err) { next(err) }
})

export default router
