package com.contract.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.contract.entity.UserWatchlist;
import com.contract.mapper.UserWatchlistMapper;
import com.contract.service.UserWatchlistService;
import org.springframework.stereotype.Service;

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

@Service
public class UserWatchlistServiceImpl extends ServiceImpl<UserWatchlistMapper, UserWatchlist>
        implements UserWatchlistService {

    @Override
    public List<UserWatchlist> listByMember(Long memberId) {
        return list(new LambdaQueryWrapper<UserWatchlist>()
                .eq(UserWatchlist::getMemberId, memberId)
                .eq(UserWatchlist::getStatus, 1)
                .orderByDesc(UserWatchlist::getSort)
                .orderByDesc(UserWatchlist::getCreatedTime));
    }

    @Override
    public void addWatchlist(Long memberId, String symbol) {
        UserWatchlist existing = getOne(new LambdaQueryWrapper<UserWatchlist>()
                .eq(UserWatchlist::getMemberId, memberId)
                .eq(UserWatchlist::getSymbol, symbol));
        LocalDateTime now = LocalDateTime.now();
        if (existing == null) {
            UserWatchlist record = new UserWatchlist();
            record.setMemberId(memberId);
            record.setSymbol(symbol);
            record.setStatus(1);
            record.setSort(0);
            record.setCreatedTime(now);
            record.setUpdatedTime(now);
            save(record);
        } else {
            update(new LambdaUpdateWrapper<UserWatchlist>()
                    .eq(UserWatchlist::getMemberId, memberId)
                    .eq(UserWatchlist::getSymbol, symbol)
                    .set(UserWatchlist::getStatus, 1)
                    .set(UserWatchlist::getUpdatedTime, now));
        }
    }

    @Override
    public void cancelWatchlist(Long memberId, String symbol) {
        update(new LambdaUpdateWrapper<UserWatchlist>()
                .eq(UserWatchlist::getMemberId, memberId)
                .eq(UserWatchlist::getSymbol, symbol)
                .set(UserWatchlist::getStatus, 2)
                .set(UserWatchlist::getUpdatedTime, LocalDateTime.now()));
    }
}
