package com.agileboot.codegen.service.impl;

import com.agileboot.codegen.entity.TemplateUsageLog;
import com.agileboot.codegen.mapper.TemplateUsageLogMapper;
import com.agileboot.codegen.service.ITemplateUsageLogService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * 模板使用日志 Service实现类
 * 
 * @author system
 * @date 2025-09-26
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TemplateUsageLogServiceImpl implements ITemplateUsageLogService {

    private final TemplateUsageLogMapper usageLogMapper;

    @Override
    @Transactional
    public void logTemplateUsage(Long userId, String templateSource, String templateId, 
                               String templateName, String templateGroup, String ipAddress) {
        try {
            TemplateUsageLog log = new TemplateUsageLog();
            log.setUserId(userId);
            log.setTemplateSource(templateSource);
            log.setTemplateId(templateId);
            log.setTemplateName(templateName);
            log.setTemplateGroup(templateGroup);
            log.setIpAddress(ipAddress);
            
            usageLogMapper.insert(log);
        } catch (Exception e) {
            // 使用日志记录不应该影响主业务流程
            log.error("记录模板使用日志失败: userId={}, templateId={}", userId, templateId, e);
        }
    }

    @Override
    public List<TemplateUsageLog> getUserUsageHistory(Long userId, Date startTime, Date endTime, Integer limit) {
        return usageLogMapper.selectUserUsageHistory(userId, 
                toLocalDateTime(startTime), 
                toLocalDateTime(endTime), 
                limit);
    }

    @Override
    public int getTemplateUsageCount(String templateSource, String templateId, Date startTime, Date endTime) {
        return usageLogMapper.countTemplateUsage(templateSource, templateId, 
                toLocalDateTime(startTime), 
                toLocalDateTime(endTime));
    }

    @Override
    public List<TemplateUsageLog> getPopularTemplates(Date startTime, Date endTime, Integer limit) {
        return usageLogMapper.selectPopularTemplates(
                toLocalDateTime(startTime), 
                toLocalDateTime(endTime), 
                limit);
    }

    /**
     * Date转LocalDateTime
     */
    private LocalDateTime toLocalDateTime(Date date) {
        return date == null ? null : date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }
}

