package com.petshop.backend.service;

import com.petshop.backend.entity.StoreLocation;
import com.petshop.backend.entity.User;
import com.petshop.backend.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

@Service
public class ActivityLogService {

    private static final Logger log = LoggerFactory.getLogger("activity");

    private final UserRepository userRepository;

    public ActivityLogService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public void record(Long userId, String activity) {
        if (userId == null || activity == null || activity.isBlank()) {
            return;
        }
        try {
            User user = userRepository.findById(userId).orElse(null);
            if (user == null) {
                return;
            }
            StoreLocation store = user.getPrimaryStore();
            String role = user.getRole() != null ? user.getRole().name() : "UNKNOWN";
            String storeName = store != null ? store.getStoreName() : "no store";
            log.info("{} | {} | {} | {}", role, user.getUsername(), storeName, activity.trim());
        } catch (Exception ex) {
            log.warn("Failed to record activity", ex);
        }
    }

    public void record(User user, String activity) {
        if (user == null) {
            return;
        }
        record(user.getId(), activity);
    }
}
