import { Router, Request, Response } from 'express';
import { z } from 'zod';
import { asyncHandler } from '../../middleware/asyncHandler';
import { authenticate } from '../../middleware/authenticate';
import { requireFeature } from '../../middleware/requireFeature';
import { requirePermission } from '../../middleware/requirePermission';
import { propertyContext } from '../../middleware/propertyContext';
import * as svc from './inventory.service';
import { getPagination } from '../../lib/pagination';

/**
 * /api/inventory (Sprint 3, TEPL): the room register, audits, work orders and
 * the general store. Rooms (MANAGE_ROOMS) run it; maintenance staff
 * (WORK_TASKS) see and move along their own work orders.
 */
export const inventoryRouter = Router();
inventoryRouter.use(authenticate, requireFeature('roomInventory'), propertyContext);

const viewerOf = (req: Request): svc.Viewer => ({ userId: req.user!.sub, role: req.user!.role, perms: req.user!.perms });
const orderBody = z.object({
  title: z.string().trim().min(3).max(120),
  description: z.string().trim().max(1000).nullable().optional(),
  roomId: z.string().uuid().nullable().optional(),
  priority: z.enum(['LOW', 'NORMAL', 'HIGH']).optional(),
  assigneeId: z.string().uuid().nullable().optional(),
  vendorId: z.string().uuid().nullable().optional(),
  dueBy: z.string().datetime().nullable().optional().transform((v) => (v ? new Date(v) : v === null ? null : undefined)),
  cost: z.number().int().min(0).max(10_000_000).nullable().optional(),
  note: z.string().trim().max(500).nullable().optional(),
});

// Work orders: the office, and the staff they are handed to.
inventoryRouter.get('/work-orders', asyncHandler(async (req: Request, res: Response) => {
  const q = z.object({ status: z.enum(['OPEN', 'IN_PROGRESS', 'DONE', 'CANCELLED']).optional(), mine: z.enum(['true', 'false']).optional() }).parse(req.query);
  const f = { status: q.status, mine: q.mine === 'true', propertyId: req.propertyId };
  // Paged when asked (Sprint L3); otherwise the first 500 as before.
  const pagination = getPagination(req.query);
  res.json(pagination ? await svc.pageOrders(viewerOf(req), f, pagination) : { workOrders: await svc.listOrders(viewerOf(req), f) });
}));
inventoryRouter.patch('/work-orders/:id', asyncHandler(async (req: Request, res: Response) => {
  const input = orderBody.partial().extend({ status: z.enum(['OPEN', 'IN_PROGRESS', 'DONE', 'CANCELLED']).optional() }).parse(req.body);
  res.json({ workOrder: await svc.updateOrder(req.params.id, viewerOf(req), input) });
}));

inventoryRouter.use(requirePermission('MANAGE_ROOMS'));
inventoryRouter.get('/options', asyncHandler(async (_req: Request, res: Response) => res.json(await svc.orderOptions())));
inventoryRouter.post('/work-orders', asyncHandler(async (req: Request, res: Response) => res.status(201).json({ workOrder: await svc.createOrder(orderBody.parse(req.body), req.user!.sub, req.propertyId) })));

inventoryRouter.get('/rooms', asyncHandler(async (req: Request, res: Response) => res.json({ rooms: await svc.registerOverview(req.propertyId) })));
inventoryRouter.post('/register/build', asyncHandler(async (req: Request, res: Response) => {
  const { propertyId } = z.object({ propertyId: z.string().uuid() }).parse(req.body);
  res.json(await svc.buildRegister(propertyId));
}));
inventoryRouter.get('/rooms/:roomId', asyncHandler(async (req: Request, res: Response) => res.json(await svc.roomRegister(req.params.roomId))));
inventoryRouter.get('/rooms/:roomId/audits', asyncHandler(async (req: Request, res: Response) => res.json({ audits: await svc.auditHistory(req.params.roomId) })));
inventoryRouter.post('/rooms/:roomId/audit', asyncHandler(async (req: Request, res: Response) => {
  const input = z.object({ items: z.array(z.object({ assetId: z.string().uuid(), status: z.enum(svc.ASSET_STATUSES), note: z.string().trim().max(200).nullable().optional() })).min(1).max(100), note: z.string().trim().max(500).nullable().optional() }).parse(req.body);
  res.status(201).json(await svc.auditRoom(req.params.roomId, input.items, req.user!.sub, input.note));
}));
inventoryRouter.post('/assets', asyncHandler(async (req: Request, res: Response) => {
  const input = z.object({ roomId: z.string().uuid(), name: z.string().trim().min(2).max(80), tag: z.string().trim().max(60).nullable().optional(), quantity: z.number().int().min(1).max(100).optional(), note: z.string().trim().max(200).nullable().optional() }).parse(req.body);
  res.status(201).json({ asset: await svc.addAsset(input) });
}));
inventoryRouter.patch('/assets/:id', asyncHandler(async (req: Request, res: Response) => {
  const input = z.object({ name: z.string().trim().min(2).max(80).optional(), tag: z.string().trim().max(60).nullable().optional(), quantity: z.number().int().min(1).max(100).optional(), status: z.enum(svc.ASSET_STATUSES).optional(), note: z.string().trim().max(200).nullable().optional() }).parse(req.body);
  res.json({ asset: await svc.updateAsset(req.params.id, input) });
}));

inventoryRouter.get('/store', asyncHandler(async (req: Request, res: Response) => res.json({ items: await svc.listStore(req.propertyId, req.query.all === 'true') })));
inventoryRouter.post('/store', asyncHandler(async (req: Request, res: Response) => {
  const input = z.object({ name: z.string().trim().min(2).max(80), unit: z.string().trim().min(1).max(20).optional(), category: z.enum(svc.STORE_CATEGORIES).optional(), reorderLevel: z.number().int().min(0).max(100000).optional(), propertyId: z.string().uuid().nullable().optional() }).parse(req.body);
  res.status(201).json({ item: await svc.createStoreItem(input) });
}));
inventoryRouter.patch('/store/:id', asyncHandler(async (req: Request, res: Response) => {
  const input = z.object({ name: z.string().trim().min(2).max(80).optional(), unit: z.string().trim().min(1).max(20).optional(), category: z.enum(svc.STORE_CATEGORIES).optional(), reorderLevel: z.number().int().min(0).max(100000).optional(), isArchived: z.boolean().optional() }).parse(req.body);
  res.json({ item: await svc.updateStoreItem(req.params.id, input) });
}));
inventoryRouter.post('/store/:id/move', asyncHandler(async (req: Request, res: Response) => {
  const input = z.object({ direction: z.enum(['IN', 'OUT']), quantity: z.number().int().min(1).max(100000), note: z.string().trim().max(200).nullable().optional(), issuedTo: z.string().trim().max(80).nullable().optional() }).parse(req.body);
  res.json({ item: await svc.moveStock(req.params.id, input, req.user!.sub) });
}));
inventoryRouter.get('/store/:id/ledger', asyncHandler(async (req: Request, res: Response) => res.json({ movements: await svc.storeLedger(req.params.id) })));
