import { Router } from 'express';
import { body, param } from 'express-validator';
import { authenticate, authorize } from '../../shared/middleware/auth';
import { validate } from '../../shared/middleware/validation';
import { productsController } from './products.controller';
import prisma from '../../config/database';
import { ResponseFormatter } from '../../shared/utils/responseFormatter';

const router = Router();
router.use(authenticate);

// ============= PRODUCTS =============

// Get all products
router.get(
  '/products',
  authorize('inventory', 'products', 'read'),
  productsController.findAll
);

// Get product by ID
router.get(
  '/products/:id',
  authorize('inventory', 'products', 'read'),
  param('id').isUUID(),
  validate,
  productsController.findById
);

// Get product history
router.get(
  '/products/:id/history',
  authorize('inventory', 'products', 'read'),
  param('id').isUUID(),
  validate,
  productsController.getHistory
);

// Create product
router.post(
  '/products',
  authorize('inventory', 'products', 'create'),
  [
    body('sku').notEmpty().trim(),
    body('name').notEmpty().trim(),
    body('categoryId').isUUID(),
    body('costPrice').isNumeric(),
    body('sellingPrice').isNumeric(),
    validate,
  ],
  productsController.create
);

// Update product
router.put(
  '/products/:id',
  authorize('inventory', 'products', 'update'),
  param('id').isUUID(),
  validate,
  productsController.update
);

// Delete product
router.delete(
  '/products/:id',
  authorize('inventory', 'products', 'delete'),
  param('id').isUUID(),
  validate,
  productsController.delete
);

// Adjust stock
router.post(
  '/products/:id/adjust-stock',
  authorize('inventory', 'products', 'update'),
  [
    param('id').isUUID(),
    body('warehouseId').isUUID(),
    body('quantity').isNumeric(),
    body('type').isIn(['ADD', 'REMOVE']),
    validate,
  ],
  productsController.adjustStock
);

// ============= CATEGORIES =============

router.get('/categories', authorize('inventory', 'categories', 'read'), async (req, res, next) => {
  try {
    const categories = await prisma.productCategory.findMany({
      where: { isActive: true },
      include: { parent: true, children: true },
      orderBy: { name: 'asc' },
    });
    res.json(ResponseFormatter.success(categories));
  } catch (error) {
    next(error);
  }
});

// Warehouses
router.get('/warehouses', authorize('inventory', 'warehouses', 'read'), async (req, res, next) => {
  try {
    const warehouses = await prisma.warehouse.findMany({
      include: { items: { include: { product: true } } },
    });
    res.json(ResponseFormatter.success(warehouses));
  } catch (error) {
    next(error);
  }
});

router.post('/warehouses', authorize('inventory', 'warehouses', 'create'), async (req, res, next) => {
  try {
    const warehouse = await prisma.warehouse.create({ data: req.body });
    res.status(201).json(ResponseFormatter.success(warehouse));
  } catch (error) {
    next(error);
  }
});

// Inventory Items
router.get('/items', authorize('inventory', 'items', 'read'), async (req, res, next) => {
  try {
    const items = await prisma.inventoryItem.findMany({
      include: {
        warehouse: true,
        product: true,
      },
    });
    res.json(ResponseFormatter.success(items));
  } catch (error) {
    next(error);
  }
});

// Assets
router.get('/assets', authorize('inventory', 'assets', 'read'), async (req, res, next) => {
  try {
    const assets = await prisma.asset.findMany({
      include: { maintenances: true },
      orderBy: { createdAt: 'desc' },
    });
    res.json(ResponseFormatter.success(assets));
  } catch (error) {
    next(error);
  }
});

router.post('/assets', authorize('inventory', 'assets', 'create'), async (req, res, next) => {
  try {
    const assetNumber = `AST-${new Date().getFullYear()}-${Date.now().toString().slice(-6)}`;
    const asset = await prisma.asset.create({
      data: { ...req.body, assetNumber },
    });
    res.status(201).json(ResponseFormatter.success(asset));
  } catch (error) {
    next(error);
  }
});

export default router;

