package org.springblade.modules.martial.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.modules.martial.mapper.MartialContactMapper;
import org.springblade.modules.martial.pojo.entity.MartialContact;
import org.springblade.modules.martial.service.IMartialContactService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * Contact Service Implementation
 */
@Slf4j
@Service
@AllArgsConstructor
public class MartialContactServiceImpl extends ServiceImpl<MartialContactMapper, MartialContact> implements IMartialContactService {

	@Override
	public IPage<MartialContact> getContactList(Long userId, Integer current, Integer size) {
		Page<MartialContact> page = new Page<>(current, size);
		LambdaQueryWrapper<MartialContact> wrapper = new LambdaQueryWrapper<>();
		wrapper.eq(MartialContact::getCreateUser, userId);
		wrapper.eq(MartialContact::getIsDeleted, 0);
		wrapper.orderByDesc(MartialContact::getIsDefault);
		wrapper.orderByDesc(MartialContact::getCreateTime);
		return this.page(page, wrapper);
	}

	@Override
	public MartialContact getContactDetail(Long id) {
		return this.getById(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean saveContact(MartialContact contact, Long userId) {
		// If setting as default, clear other defaults first
		if (Boolean.TRUE.equals(contact.getIsDefault())) {
			LambdaUpdateWrapper<MartialContact> updateWrapper = new LambdaUpdateWrapper<>();
			updateWrapper.eq(MartialContact::getCreateUser, userId)
						 .eq(MartialContact::getIsDeleted, 0)
						 .set(MartialContact::getIsDefault, false);
			// Exclude current contact if it's an update
			if (contact.getId() != null) {
				updateWrapper.ne(MartialContact::getId, contact.getId());
			}
			this.update(updateWrapper);
			log.info("Cleared default status for user {}'s other contacts", userId);
		}
		
		// Set audit fields
		if (contact.getId() == null) {
			contact.setCreateUser(userId);
			contact.setCreateTime(new Date());
		}
		contact.setUpdateUser(userId);
		contact.setUpdateTime(new Date());
		
		return this.saveOrUpdate(contact);
	}

}
