import express from 'express';
import * as companyController from '../controllers/company.controller.js';
import * as personalContactController from '../controllers/personal-contact.controller.js';
import { authenticate } from '../middlewares/auth/authMiddleware.js';
import { requireAdmin } from '../middlewares/auth/roleMiddleware.js';
import { checkCompanyAccess } from '../middlewares/auth/resourceAccessMiddleware.js';
import { validateBody, validateParams } from '../middlewares/security/validateInput.js';
import { createCompanySchema, updateCompanySchema, createCompanyReminderSchema, updateCompanyReminderSchema } from '../validators/crm.validators.js';
import { z } from 'zod';

const router = express.Router();

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

// Reminder summaries (must be before :companyId routes)
router.get('/reminders/summary', companyController.getReminderSummary);
router.get('/reminders/counts', companyController.getReminderCountsByCompany);
router.get('/reminders/upcoming', companyController.getUpcomingReminders);

// Company unread email summary
router.get('/email-unread', companyController.getCompanyUnreadCounts);

// Company email threads
router.get(
  '/:companyId/email-threads',
  validateParams(z.object({ companyId: z.string().uuid() })),
  checkCompanyAccess,
  companyController.getCompanyEmailThreads
);

/**
 * Company management
 */

// Get all companies
router.get('/', companyController.getAllCompanies);

// Get company by ID
router.get(
  '/:companyId',
  validateParams(z.object({ companyId: z.string().uuid() })),
  checkCompanyAccess,
  companyController.getCompanyById
);

// Create new company (admin only)
router.post(
  '/',
  requireAdmin,
  validateBody(createCompanySchema),
  companyController.createCompany
);

// Update company (admin only)
router.patch(
  '/:companyId',
  requireAdmin,
  validateParams(z.object({ companyId: z.string().uuid() })),
  validateBody(updateCompanySchema),
  companyController.updateCompany
);

// Delete company (admin only)
router.delete(
  '/:companyId',
  requireAdmin,
  validateParams(z.object({ companyId: z.string().uuid() })),
  companyController.deleteCompany
);

// Company Notes (nested resources)
router.get(
  '/:companyId/notes',
  validateParams(z.object({ companyId: z.string().uuid() })),
  checkCompanyAccess,
  companyController.getCompanyNotes
);

router.post(
  '/:companyId/notes',
  requireAdmin,
  validateParams(z.object({ companyId: z.string().uuid() })),
  validateBody(z.object({
    content: z.string().min(1),
    dueDate: z.string().optional().or(z.literal('')),
  })),
  companyController.addCompanyNote
);

router.patch(
  '/:companyId/notes/:noteId',
  requireAdmin,
  validateParams(z.object({
    companyId: z.string().uuid(),
    noteId: z.string().uuid()
  })),
  validateBody(z.object({
    content: z.string().min(1).optional(),
    dueDate: z.string().optional().or(z.literal('').or(z.null())),
  })),
  companyController.updateCompanyNote
);

router.delete(
  '/:companyId/notes/:noteId',
  requireAdmin,
  validateParams(z.object({
    companyId: z.string().uuid(),
    noteId: z.string().uuid()
  })),
  companyController.deleteCompanyNote
);

// Company reminders
router.get(
  '/:companyId/reminders',
  validateParams(z.object({ companyId: z.string().uuid() })),
  checkCompanyAccess,
  companyController.getCompanyReminders
);

router.post(
  '/:companyId/reminders',
  requireAdmin,
  validateParams(z.object({ companyId: z.string().uuid() })),
  validateBody(createCompanyReminderSchema),
  companyController.createCompanyReminder
);

router.patch(
  '/:companyId/reminders/:reminderId',
  requireAdmin,
  validateParams(z.object({
    companyId: z.string().uuid(),
    reminderId: z.string().uuid()
  })),
  validateBody(updateCompanyReminderSchema),
  companyController.updateCompanyReminder
);

router.delete(
  '/:companyId/reminders/:reminderId',
  requireAdmin,
  validateParams(z.object({
    companyId: z.string().uuid(),
    reminderId: z.string().uuid()
  })),
  companyController.deleteCompanyReminder
);

// Company Users (Team Management)
router.get(
  '/:companyId/users',
  validateParams(z.object({ companyId: z.string().uuid() })),
  checkCompanyAccess,
  companyController.getCompanyUsers
);

router.post(
  '/:companyId/users',
  requireAdmin,
  validateParams(z.object({ companyId: z.string().uuid() })),
  validateBody(z.object({
    userId: z.string().uuid(),
    role: z.string().optional(),
  })),
  companyController.assignUserToCompany
);

router.patch(
  '/:companyId/users/:userId',
  requireAdmin,
  validateParams(z.object({
    companyId: z.string().uuid(),
    userId: z.string().uuid()
  })),
  validateBody(z.object({
    role: z.string().optional(),
  })),
  companyController.updateUserRoleOnCompany
);

router.delete(
  '/:companyId/users/:userId',
  requireAdmin,
  validateParams(z.object({
    companyId: z.string().uuid(),
    userId: z.string().uuid()
  })),
  companyController.removeUserFromCompany
);

// Company Contacts (Personal contacts linked to company)
router.get(
  '/:companyId/contacts',
  validateParams(z.object({ companyId: z.string().uuid() })),
  checkCompanyAccess,
  personalContactController.getContactsByCompany
);

export default router;
