package com.dji.sample.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dji.sample.common.util.SecurityUtils;
import com.dji.sample.manage.dao.IUserPasswordHistoryMapper;
import com.dji.sample.manage.model.entity.UserPasswordHistoryEntity;
import com.dji.sample.manage.service.IUserPasswordHistoryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UserPasswordHistoryServiceImpl
        extends ServiceImpl<IUserPasswordHistoryMapper, UserPasswordHistoryEntity>
        implements IUserPasswordHistoryService {

    @Override
    public void savePasswordHistory(String userId, String workspaceId, String encodedPassword, int maxHistory) {
        // Insert new record
        UserPasswordHistoryEntity record = new UserPasswordHistoryEntity();
        record.setUserId(userId);
        record.setWorkspaceId(workspaceId);
        record.setPassword(encodedPassword);
        this.save(record);

        // Prune old records – keep only the most recent maxHistory entries
        LambdaQueryWrapper<UserPasswordHistoryEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserPasswordHistoryEntity::getUserId, userId)
               .orderByAsc(UserPasswordHistoryEntity::getCreateTime);
        List<UserPasswordHistoryEntity> history = this.list(wrapper);

        if (history.size() > maxHistory) {
            int toDelete = history.size() - maxHistory;
            // oldest records come first due to orderByAsc
            for (int i = 0; i < toDelete; i++) {
                this.removeById(history.get(i).getId());
            }
        }
    }

    @Override
    public boolean isPasswordRecentlyUsed(String userId, String rawPassword, int maxHistory) {
        LambdaQueryWrapper<UserPasswordHistoryEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserPasswordHistoryEntity::getUserId, userId)
               .orderByDesc(UserPasswordHistoryEntity::getCreateTime)
               .last("LIMIT " + maxHistory);
        List<UserPasswordHistoryEntity> history = this.list(wrapper);

        return history.stream()
                .anyMatch(h -> SecurityUtils.matchesPassword(rawPassword, h.getPassword()));
    }

}
