package ru.soune.nocopy.service.user;

import org.springframework.data.jpa.domain.Specification;
import ru.soune.nocopy.entity.user.SubscriptionType;
import ru.soune.nocopy.entity.user.User;

import java.time.LocalDate;

public class UserSpecifications {

    public static Specification<User> byFullName(String fullName) {
        return (root, query, cb) -> {
            if (fullName == null || fullName.isEmpty()) return null;
            return cb.like(cb.lower(root.get("fullName")), "%" + fullName.toLowerCase() + "%");
        };
    }

    public static Specification<User> byEmail(String email) {
        return (root, query, cb) -> {
            if (email == null || email.isEmpty()) return null;
            return cb.like(cb.lower(root.get("email")), "%" + email.toLowerCase() + "%");
        };
    }

    public static Specification<User> byIsActive(Boolean isActive) {
        return (root, query, cb) -> {
            if (isActive == null) return null;
            return cb.equal(root.get("isActive"), isActive);
        };
    }

    public static Specification<User> byEmailVerified(Boolean emailVerified) {
        return (root, query, cb) -> {
            if (emailVerified == null) return null;
            return cb.equal(root.get("emailVerified"), emailVerified);
        };
    }

    public static Specification<User> bySubscriptionType(SubscriptionType type) {
        return (root, query, cb) -> {
            if (type == null) return null;
            return cb.equal(root.get("subscriptionType"), type);
        };
    }

    public static Specification<User> byCreatedAtRange(LocalDate from, LocalDate to) {
        return (root, query, cb) -> {
            if (from == null && to == null) return null;
            if (from != null && to != null) {
                return cb.between(root.get("createdAt"),
                        from.atStartOfDay(), to.atTime(23, 59, 59));
            } else if (from != null) {
                return cb.greaterThanOrEqualTo(root.get("createdAt"), from.atStartOfDay());
            } else {
                return cb.lessThanOrEqualTo(root.get("createdAt"), to.atTime(23, 59, 59));
            }
        };
    }
}
