import * as favoritesRepo from '../repositories/favorites.repository';
import * as propertiesRepo from '../repositories/properties.repository';

export const getUserFavorites = async (userId: number | null, visitorToken: string | null) => {
  if (userId) return await favoritesRepo.findAllForUser(userId);
  if (visitorToken) return await favoritesRepo.findAllForVisitor(visitorToken);
  return [];
};

export const checkIsFavorite = async (propertyId: number, userId: number | null, visitorToken: string | null) => {
  if (userId) {
    const fav = await favoritesRepo.findByPropertyAndUser(propertyId, userId);
    return !!fav;
  }
  if (visitorToken) {
    const fav = await favoritesRepo.findByPropertyAndVisitor(propertyId, visitorToken);
    return !!fav;
  }
  return false;
};

export const addFavorite = async (propertyId: number, userId: number | null, visitorToken: string | null) => {
  if (!userId && !visitorToken) throw new Error('Utilisateur non identifié');

  const property = await propertiesRepo.findById(propertyId);
  if (!property) throw new Error('Bien introuvable');
  if (property.property_status !== 'AVAILABLE') throw new Error('Ce bien n\'est plus disponible');

  await favoritesRepo.create(propertyId, userId, visitorToken);
};

export const removeFavorite = async (propertyId: number, userId: number | null, visitorToken: string | null) => {
  if (!userId && !visitorToken) throw new Error('Utilisateur non identifié');
  
  await favoritesRepo.remove(propertyId, userId, visitorToken);
};
