package com.bizzan.bitrade.service;

import com.bizzan.bitrade.dao.DeviceBlacklistDao;
import com.bizzan.bitrade.dao.MemberDeviceDao;
import com.bizzan.bitrade.entity.MemberDevice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.Optional;

@Service
public class MemberDeviceService {

    @Autowired
    private DeviceBlacklistDao deviceBlacklistDao;

    @Autowired
    private MemberDeviceDao memberDeviceDao;

    public boolean isBlacklisted(String deviceFingerprint) {
        if (!StringUtils.hasText(deviceFingerprint)) return false;
        return deviceBlacklistDao.existsByDeviceFingerprint(deviceFingerprint);
    }

    @Transactional(rollbackFor = Exception.class)
    public void recordLogin(Long memberId, String deviceFingerprint,
                            Integer deviceType, String deviceModel,
                            String osVersion, String ip) {
        if (!StringUtils.hasText(deviceFingerprint)) return;

        Date now = new Date();
        int updated = memberDeviceDao.updateLogin(memberId, deviceFingerprint, ip, now);
        if (updated == 0) {
            MemberDevice device = new MemberDevice();
            device.setMemberId(memberId);
            device.setDeviceFingerprint(deviceFingerprint);
            device.setDeviceType(deviceType);
            device.setDeviceModel(deviceModel);
            device.setOsVersion(osVersion);
            device.setFirstLoginTime(now);
            device.setLastLoginTime(now);
            device.setLastLoginIp(ip);
            device.setLoginCount(1);
            memberDeviceDao.save(device);
        }
    }
}
