import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authenticate } from '../../middleware/authenticate';
import { deviceAuth } from '../../middleware/deviceAuth';
import { requireFeature, tenantHasFeature } from '../../middleware/requireFeature';
import { requirePermission } from '../../middleware/requirePermission';
import { ForbiddenError } from '../../lib/errors';
import * as svc from './integrations.service';

/**
 * /api/integrations (Sprint 6, TEPL): TEPL's roster and HR systems push with
 * an HR_FEED device key; the office uploads the same rows as a file and
 * watches the runs.
 */
export const integrationsRouter = Router();

const rosterRows = z.array(z.object({ employeeCode: z.string().trim().min(1).max(40), date: z.string().trim().min(6).max(20), shift: z.string().trim().min(1).max(10) })).min(1).max(20000);
const leaveRows = z
  .array(
    z.object({
      ref: z.string().trim().min(1).max(80),
      employeeCode: z.string().trim().min(1).max(40),
      leaveType: z.string().trim().min(1).max(20),
      from: z.string().trim().min(6).max(20),
      to: z.string().trim().min(6).max(20),
      halfDay: z.boolean().optional(),
      status: z.enum(['APPROVED', 'CANCELLED']).optional(),
      note: z.string().trim().max(300).nullable().optional(),
    }),
  )
  .min(1)
  .max(5000);

async function feedDevice(req: Request) {
  if (req.device!.purpose !== 'HR_FEED') throw new ForbiddenError('Only an HR feed key can send the roster or plant leave');
  if (!(await tenantHasFeature(req.device!.tenantId, 'hrFeeds'))) throw new ForbiddenError('The HR feeds are not switched on for this account', 'FEATURE_OFF');
}

// The machines.
integrationsRouter.post('/roster', deviceAuth, asyncHandler(async (req: Request, res: Response) => {
  await feedDevice(req);
  res.status(201).json(await svc.rosterFeed(z.object({ entries: rosterRows }).parse(req.body).entries, 'FEED', req.device!.id));
}));
integrationsRouter.post('/plant-leave', deviceAuth, asyncHandler(async (req: Request, res: Response) => {
  await feedDevice(req);
  res.status(201).json(await svc.plantLeaveFeed(z.object({ leaves: leaveRows }).parse(req.body).leaves, 'FEED', req.device!.id));
}));

// The office.
integrationsRouter.use(authenticate, requireFeature('hrFeeds'), requirePermission('MANAGE_STUDENTS'));
integrationsRouter.get('/runs', asyncHandler(async (req: Request, res: Response) => res.json(await svc.runs(z.enum(['ROSTER', 'PLANT_LEAVE']).optional().parse(req.query.kind)))));
// A plant-approved leave issues a pass and stops meals: whoever uploads the file must hold the plant's approval right too.
integrationsRouter.post('/plant-leave/file', requirePermission('APPROVE_PLANT_LEAVE'), asyncHandler(async (req: Request, res: Response) => res.json(await svc.plantLeaveFeed(z.object({ leaves: leaveRows }).parse(req.body).leaves, 'FILE', null, req.user!.sub))));
