import { Router } from 'express';
import { body, param } from 'express-validator';
import multer from 'multer';
import { contactsController } from './contacts.controller';
import { authenticate, authorize } from '../../shared/middleware/auth';
import { validate } from '../../shared/middleware/validation';
import categoriesRouter from './categories.routes';

const router = Router();
const upload = multer({ storage: multer.memoryStorage() });

// All routes require authentication
router.use(authenticate);

// Get all contacts
router.get(
  '/',
  authorize('contacts', 'contacts', 'read'),
  contactsController.findAll
);

// Get contact by ID
router.get(
  '/:id',
  authorize('contacts', 'contacts', 'read'),
  param('id').isUUID(),
  validate,
  contactsController.findById
);

// Get contact history
router.get(
  '/:id/history',
  authorize('contacts', 'contacts', 'read'),
  param('id').isUUID(),
  validate,
  contactsController.getHistory
);

// Create contact
router.post(
  '/',
  authorize('contacts', 'contacts', 'create'),
  [
    body('type').isIn(['INDIVIDUAL', 'COMPANY', 'HOLDING', 'GOVERNMENT','ORGANIZATION','EMBASSIES',
  'BANK','UNIVERSITY','SCHOOL','UN','NGO','INSTITUTION','SUPPLIER',]),
    body('name').notEmpty().trim(),
    body('email').optional().isEmail(),
    body('source').notEmpty(),
    validate,
  ],
  contactsController.create
);

// Update contact
router.put(
  '/:id',
  authorize('contacts', 'contacts', 'update'),
  [
    param('id').isUUID(),
    body('type')
      .optional()
      .isIn([
        'INDIVIDUAL',
        'COMPANY',
        'HOLDING',
        'GOVERNMENT',
        'ORGANIZATION',
        'EMBASSIES',
        'BANK',
        'UNIVERSITY',
        'SCHOOL',
        'UN',
        'NGO',
        'INSTITUTION',
        'SUPPLIER',
      ]),
    body('email')
      .optional({ values: 'falsy' })
      .custom((value) => {
        if (value === null || value === undefined || value === '') return true
        return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)
      })
      .withMessage('Invalid email format'),
    validate,
  ],
  contactsController.update
);

// Archive contact
router.post(
  '/:id/archive',
  authorize('contacts', 'contacts', 'archive'),
  param('id').isUUID(),
  validate,
  contactsController.archive
);

// Hard delete contact (GM only)
router.delete(
  '/:id',
  authorize('contacts', 'contacts', 'delete'),
  [
    param('id').isUUID(),
    body('reason').notEmpty().withMessage('السبب مطلوب - Reason required'),
    validate,
  ],
  contactsController.delete
);

// Merge contacts
router.post(
  '/merge',
  authorize('contacts', 'contacts', 'merge'),
  [
    body('sourceId').isUUID(),
    body('targetId').isUUID(),
    body('reason').notEmpty().withMessage('السبب مطلوب - Reason required'),
    validate,
  ],
  contactsController.merge
);

// Get relationships for a contact
router.get(
  '/:id/relationships',
  authorize('contacts', 'contacts', 'read'),
  param('id').isUUID(),
  validate,
  contactsController.getRelationships
);

// Add relationship
router.post(
  '/:id/relationships',
  authorize('contacts', 'contacts', 'create'),
  [
    param('id').isUUID(),
    body('toContactId').isUUID(),
    body('type').notEmpty(),
    body('startDate').isISO8601(),
    body('endDate').optional().isISO8601(),
    body('notes').optional(),
    validate,
  ],
  contactsController.addRelationship
);

// Update relationship
router.put(
  '/:id/relationships/:relationshipId',
  authorize('contacts', 'contacts', 'update'),
  [
    param('id').isUUID(),
    param('relationshipId').isUUID(),
    body('type').optional(),
    body('startDate').optional().isISO8601(),
    body('endDate').optional().isISO8601(),
    body('notes').optional(),
    body('isActive').optional().isBoolean(),
    validate,
  ],
  contactsController.updateRelationship
);

// Delete relationship
router.delete(
  '/:id/relationships/:relationshipId',
  authorize('contacts', 'contacts', 'delete'),
  [
    param('id').isUUID(),
    param('relationshipId').isUUID(),
    validate,
  ],
  contactsController.deleteRelationship
);

// Check for duplicates
router.post(
  '/check-duplicates',
  authorize('contacts', 'contacts', 'read'),
  [
    body('email').optional().isEmail(),
    body('phone').optional(),
    body('mobile').optional(),
    body('taxNumber').optional(),
    body('commercialRegister').optional(),
    body('excludeId').optional().isUUID(),
    validate,
  ],
  contactsController.checkDuplicates
);

// Import contacts
router.post(
  '/import',
  authorize('contacts', 'contacts', 'create'),
  upload.single('file'),
  contactsController.import
);

// Export contacts
router.get(
  '/export',
  authorize('contacts', 'contacts', 'read'),
  contactsController.export
);

// Mount categories router
router.use('/categories', categoriesRouter);

export default router;

