package com.izouma.nineth.service;

import com.izouma.nineth.domain.UserCoupon;
import com.izouma.nineth.dto.PageQuery;
import com.izouma.nineth.repo.UserCouponRepo;
import com.izouma.nineth.utils.JpaUtils;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
@AllArgsConstructor
public class UserCouponService {

    private UserCouponRepo userCouponRepo;

    public Page<UserCoupon> all(PageQuery pageQuery) {
        String status = (String) pageQuery.getQuery().get("status");
        if (StringUtils.hasText(status)) {
            if ("OVERDUE".equals(status)) {
                List<String> list = new ArrayList<>(1);
                pageQuery.getQuery().put("expiration", list);
            }
            if ("CAN_USE".equals(status)) {
                List<String> list = new ArrayList<>(1);
                list.add(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                pageQuery.getQuery().put("expiration", list);
                pageQuery.getQuery().put("used", false);
            }
        }
        return userCouponRepo.findAll(JpaUtils.toSpecification(pageQuery, UserCoupon.class), JpaUtils.toPageRequest(pageQuery));
    }
}
