import express from 'express';
import * as crmEmailController from '../controllers/crm-email.controller.js';
import { authenticate } from '../middlewares/auth/authMiddleware.js';
import { requireAccountId } from '../middlewares/security/requireAccountId.js';
import { validateBody, validateParams } from '../middlewares/security/validateInput.js';
import { z } from 'zod';

const router = express.Router();

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

/**
 * Email management
 */

// Get all emails (accountId required)
router.get('/', requireAccountId, crmEmailController.getEmails);

// Search emails (DB search - searches in stored emails only, accountId required)
router.get('/search', requireAccountId, crmEmailController.searchEmails);

// Search emails using JMAP full-text search (searches in all emails via JMAP)
router.get('/search-jmap', crmEmailController.searchEmailsJMAP);

// Get unread count
router.get('/unread-count', crmEmailController.getUnreadCount);

// Sync latest emails from JMAP
router.post('/sync', crmEmailController.syncEmails);

// Get email thread (conversation, accountId required)
router.get(
  '/thread/:threadId',
  requireAccountId,
  validateParams(z.object({ threadId: z.string() })),
  crmEmailController.getThread
);

// Mark thread as read (accountId required)
router.post(
  '/thread/:threadId/read',
  requireAccountId,
  validateParams(z.object({ threadId: z.string() })),
  crmEmailController.markThreadRead
);

// Mark all emails from contact as read (accountId required)
router.post(
  '/contact/:contactId/read',
  requireAccountId,
  validateParams(z.object({ contactId: z.string().uuid() })),
  crmEmailController.markContactEmailsRead
);

// Send email reply
router.post(
  '/reply',
  validateBody(
    z.object({
      to: z.string().email('Neplatný formát emailu'),
      subject: z.string().min(1, 'Subject nemôže byť prázdny'),
      body: z.string().min(1, 'Telo emailu nemôže byť prázdne'),
      inReplyTo: z.string().optional(),
      threadId: z.string().optional(),
    })
  ),
  crmEmailController.replyToEmail
);

export default router;
