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 { propertyContext } from '../../middleware/propertyContext';
import { BadRequestError, ForbiddenError } from '../../lib/errors';
import * as svc from './energy.service';
import * as kpi from './energy-kpi.service';

/**
 * /api/energy (Sprint 3, TEPL). The BMS pushes readings with a device key
 * (a device registered with purpose BMS); the office sets up meters.
 */
export const energyRouter = Router();

const readingsBody = z.object({
  readings: z.array(z.object({ meter: z.string().trim().min(1).max(60), readAt: z.string().min(10).max(40), kwh: z.number() })).min(1).max(20_000),
});

// The BMS. A terminal key cannot post readings, nor a BMS key punches.
energyRouter.post(
  '/readings',
  deviceAuth,
  asyncHandler(async (req: Request, res: Response) => {
    if (req.device!.purpose !== 'BMS') throw new ForbiddenError('Only a BMS device can send meter readings');
    if (!(await tenantHasFeature(req.device!.tenantId, 'energy'))) throw new ForbiddenError('Energy is not switched on for this account', 'FEATURE_OFF');
    const { readings } = readingsBody.parse(req.body);
    res.status(201).json(await svc.ingestReadings(readings, req.header('x-reading-source') === 'SIMULATOR' ? 'SIMULATOR' : 'BMS'));
  }),
);

energyRouter.use(authenticate, requireFeature('energy'), propertyContext, requirePermission('MANAGE_PROPERTY'));
const meterBody = z.object({
  propertyId: z.string().uuid(),
  roomId: z.string().uuid().nullable().optional(),
  code: z.string().trim().min(1).max(60),
  name: z.string().trim().min(1).max(80),
  kind: z.enum(['ROOM', 'COMMON']).optional(),
  multiplier: z.number().positive().max(10000).optional(),
  isActive: z.boolean().optional(),
});
energyRouter.get('/meters', asyncHandler(async (req: Request, res: Response) => res.json({ meters: await svc.lastReadings(req.propertyId) })));
energyRouter.post('/meters', asyncHandler(async (req: Request, res: Response) => res.status(201).json({ meter: await svc.createMeter(meterBody.parse(req.body)) })));
energyRouter.patch('/meters/:id', asyncHandler(async (req: Request, res: Response) => res.json({ meter: await svc.updateMeter(req.params.id, meterBody.omit({ propertyId: true }).partial().parse(req.body)) })));
energyRouter.post('/meters/import', asyncHandler(async (req: Request, res: Response) => {
  const { rows } = z.object({ rows: z.array(z.object({ code: z.string().trim().min(1).max(60), block: z.string().trim().max(120).nullable().optional(), room: z.string().trim().max(20).nullable().optional(), name: z.string().trim().max(80).nullable().optional() })).min(1).max(5000) }).parse(req.body);
  res.json(await svc.importMeters(rows, req.propertyId));
}));
/** Readings typed in by hand (a meter the BMS does not reach). */
energyRouter.post('/readings/manual', asyncHandler(async (req: Request, res: Response) => {
  const { readings } = readingsBody.parse(req.body);
  if (readings.length > 500) throw new BadRequestError('Up to 500 readings at a time by hand');
  res.status(201).json(await svc.ingestReadings(readings, 'MANUAL'));
}));

// ── Sprint 4 (TEPL): KPIs, high-use alerts, the BMS connection ──────────────

energyRouter.get('/kpis', asyncHandler(async (req: Request, res: Response) => {
  const month = z.string().regex(/^\d{4}-\d{2}$/).optional().parse(req.query.month) ?? new Date(Date.now() + 330 * 60_000).toISOString().slice(0, 7);
  res.json(await kpi.kpis(month, req.propertyId));
}));
energyRouter.get('/alerts', asyncHandler(async (req: Request, res: Response) => res.json({ alerts: await kpi.listAlerts(z.enum(['OPEN', 'ACKNOWLEDGED']).optional().parse(req.query.status), req.propertyId) })));
/** Check a day for high use now (the hourly pass checks yesterday after 1 am). */
energyRouter.post('/alerts/run', asyncHandler(async (req: Request, res: Response) => {
  const day = z.object({ day: z.string().regex(/^\d{4}-\d{2}-\d{2}$/) }).parse(req.body).day;
  res.json({ day, newAlerts: (await kpi.checkHighUse(day)).length });
}));
energyRouter.post('/alerts/:id/ack', asyncHandler(async (req: Request, res: Response) => res.json({ alert: await kpi.ackAlert(req.params.id, req.user!.sub) })));
energyRouter.get('/settings', asyncHandler(async (_req: Request, res: Response) => res.json({ settings: await kpi.getSettings() })));
energyRouter.put('/settings', asyncHandler(async (req: Request, res: Response) => {
  const input = z
    .object({
      bmsPullUrl: z.string().trim().max(300).nullable().optional(),
      bmsToken: z.string().trim().max(500).nullable().optional(),
      alertRatio: z.number().min(1.1).max(10).optional(),
      alertMinKwh: z.number().min(0).max(1000).optional(),
    })
    .parse(req.body);
  res.json({ settings: await kpi.saveSettings(input) });
}));
/** Pull from the BMS now (pull mode), to test the connection. */
energyRouter.post('/settings/pull', asyncHandler(async (_req: Request, res: Response) => {
  const result = await kpi.pullFromBms();
  if (!result) throw new BadRequestError('No BMS address is set for pull mode');
  res.json({ result, settings: await kpi.getSettings() });
}));
