package com.yaoyuan.jiscuss.service;

import com.yaoyuan.jiscuss.entity.AuditLog;
import com.yaoyuan.jiscuss.entity.UserInfo;
import com.yaoyuan.jiscuss.repository.AuditLogRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * Service for recording admin operations in audit log.
 */
@Service
public class AuditLogService {

    private final AuditLogRepository auditLogRepository;

    public AuditLogService(AuditLogRepository auditLogRepository) {
        this.auditLogRepository = auditLogRepository;
    }

    @Transactional
    public void log(Integer adminId, String adminName, String actionType, String targetType,
                    Integer targetId, String description, String status) {
        AuditLog log = new AuditLog();
        log.setAdminId(adminId);
        log.setAdminName(adminName);
        log.setActionType(actionType);
        log.setTargetType(targetType);
        log.setTargetId(targetId);
        log.setDescription(description);
        log.setStatus(status == null ? "success" : status);
        log.setCreateTime(new Date());
        auditLogRepository.save(log);
    }

    @Transactional
    public void log(Integer adminId, String adminName, String actionType, String targetType,
                    Integer targetId, String description) {
        log(adminId, adminName, actionType, targetType, targetId, description, "success");
    }

    @Transactional
    public void log(UserInfo user, String actionType, String targetType,
                    Integer targetId, String description) {
        Integer userId = user == null ? null : user.getId();
        String userName = user == null ? "unknown" : user.getUsername();
        log(userId, userName, actionType, targetType, targetId, description, "success");
    }

    @Transactional
    public void log(UserInfo user, String actionType, String targetType,
                    Integer targetId, String description, String status) {
        Integer userId = user == null ? null : user.getId();
        String userName = user == null ? "unknown" : user.getUsername();
        log(userId, userName, actionType, targetType, targetId, description, status);
    }
}
