package com.tasteby.service;

import com.tasteby.domain.Memo;
import com.tasteby.mapper.MemoMapper;
import com.tasteby.util.IdGenerator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

@Service
public class MemoService {

    private final MemoMapper mapper;

    public MemoService(MemoMapper mapper) {
        this.mapper = mapper;
    }

    public Memo findByUserAndRestaurant(String userId, String restaurantId) {
        return mapper.findByUserAndRestaurant(userId, restaurantId);
    }

    @Transactional
    public Memo upsert(String userId, String restaurantId, Double rating, String memoText, LocalDate visitedAt) {
        String visitedStr = visitedAt != null ? visitedAt.toString() : null;
        Memo existing = mapper.findByUserAndRestaurant(userId, restaurantId);
        if (existing != null) {
            mapper.updateMemo(userId, restaurantId, rating, memoText, visitedStr);
        } else {
            mapper.insertMemo(IdGenerator.newId(), userId, restaurantId, rating, memoText, visitedStr);
        }
        return mapper.findByUserAndRestaurant(userId, restaurantId);
    }

    public boolean delete(String userId, String restaurantId) {
        return mapper.deleteMemo(userId, restaurantId) > 0;
    }

    public List<Memo> findByUser(String userId) {
        return mapper.findByUser(userId);
    }
}
