import * as contactMessagesRepo from '../repositories/contactMessages.repository';
import * as auditRepo from '../repositories/audit.repository';

export const getMessages = async (page: number, limit: number, search?: string, status?: string) => {
  return await contactMessagesRepo.findAllPaginated(page, limit, search, status);
};

export const getMessageById = async (id: number) => {
  return await contactMessagesRepo.findById(id);
};

export const createMessage = async (data: any) => {
  const id = await contactMessagesRepo.create(data);
  // Notify admins
  const notificationsService = await import('./notifications.service');
  await notificationsService.notifyStaff(
    'CONTACT',
    'Nouveau message de contact',
    `Un visiteur (${data.first_name} ${data.last_name}) a envoyé un message depuis le site.`
  );
  
  setImmediate(async () => {
    try {
      const { sendExternalNotification } = await import('./notificationSender.service');
      await sendExternalNotification('CONTACT', data);
    } catch (err) {
      console.error('Erreur lors de l\'envoi de la notification de contact:', err);
    }
  });
  
  return { id, ...data };
};

export const updateMessageStatus = async (id: number, status: string, userId: number, ip: string, userAgent?: string) => {
  const message = await contactMessagesRepo.findById(id);
  if (!message) throw new Error('Message introuvable');

  await contactMessagesRepo.update(id, { status });

  await auditRepo.createAuditLog({
    user_id: userId,
    action: 'UPDATE_STATUS',
    entity_type: 'CONTACT_MESSAGE',
    entity_id: id,
    old_values: { status: message.status },
    new_values: { status },
    ip_address: ip,
    user_agent: userAgent
  });
};

export const assignMessage = async (id: number, handled_by: number | null, userId: number, ip: string, userAgent?: string) => {
  const message = await contactMessagesRepo.findById(id);
  if (!message) throw new Error('Message introuvable');

  await contactMessagesRepo.update(id, { handled_by });

  await auditRepo.createAuditLog({
    user_id: userId,
    action: 'ASSIGN',
    entity_type: 'CONTACT_MESSAGE',
    entity_id: id,
    old_values: { handled_by: message.handled_by },
    new_values: { handled_by },
    ip_address: ip,
    user_agent: userAgent
  });
};
