import express from 'express';
import * as contactController from '../controllers/contact.controller.js';
import { authenticate } from '../middlewares/auth/authMiddleware.js';
import { validateBody, validateParams } from '../middlewares/security/validateInput.js';
import { z } from 'zod';

const router = express.Router();

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

/**
 * Contact management
 */

// Get all contacts
router.get('/', contactController.getContacts);

// Discover potential contacts from JMAP
router.get('/discover', contactController.discoverContacts);

// Add a new contact
router.post(
  '/',
  validateBody(
    z.object({
      email: z.string().email('Neplatný formát emailu'),
      name: z.string().optional(),
      notes: z.string().optional(),
      accountId: z.string().uuid().optional(),
    })
  ),
  contactController.addContact
);

// Update a contact
router.patch(
  '/:contactId',
  validateParams(z.object({ contactId: z.string().uuid() })),
  validateBody(
    z.object({
      name: z.string().optional(),
      notes: z.string().optional(),
    })
  ),
  contactController.updateContact
);

// Link company to contact
router.post(
  '/:contactId/link-company',
  validateParams(z.object({ contactId: z.string().uuid() })),
  validateBody(z.object({ companyId: z.string().uuid() })),
  contactController.linkCompanyToContact
);

// Unlink company from contact
router.post(
  '/:contactId/unlink-company',
  validateParams(z.object({ contactId: z.string().uuid() })),
  contactController.unlinkCompanyFromContact
);

// Create company from contact
router.post(
  '/:contactId/create-company',
  validateParams(z.object({ contactId: z.string().uuid() })),
  validateBody(
    z.object({
      name: z.string().optional(),
      email: z.string().email().optional(),
      phone: z.string().optional(),
      address: z.string().optional(),
      city: z.string().optional(),
      country: z.string().optional(),
      website: z.string().optional(),
      description: z.string().optional(),
    })
  ),
  contactController.createCompanyFromContact
);

// Remove a contact
router.delete(
  '/:contactId',
  validateParams(z.object({ contactId: z.string().uuid() })),
  contactController.removeContact
);

export default router;
