package ru.soune.nocopy.repository;

import jakarta.validation.constraints.Size;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import ru.soune.nocopy.entity.tarif.TariffInfo;
import ru.soune.nocopy.entity.user.User;

import java.util.List;
import java.util.Optional;

public interface UserRepository extends JpaRepository<User, Long> {
    User findByEmail(String email);
    boolean existsByEmail(String email);
    boolean existsByPhone(@Size(min = 11, max = 14) String phone);
    List<User> findByCompanyId(String companyId);
    long countByCompanyId(String companyId);
    User findByPersonalTariffInfo(TariffInfo tariffInfo);

    @Query("SELECT COUNT(u.Id) FROM User u")
    Long getTotalUsersCount();

    @Query(value = """
        SELECT COUNT(*)
        FROM users
        WHERE created_at >= NOW() - INTERVAL '1 day' * :days
    """, nativeQuery = true)
    Long getNewUsersCount(int days);

    @Query(value = """
        SELECT COUNT(*)
        FROM users
        WHERE created_at >= DATE_TRUNC('month', NOW())
    """, nativeQuery = true)
    Long getNewUsersCurrentMonth();

    @Query(value = """
        SELECT COUNT(*)
        FROM users
        WHERE created_at >= DATE_TRUNC('month', NOW() - INTERVAL '1 month')
          AND created_at < DATE_TRUNC('month', NOW())
    """, nativeQuery = true)
    Long getNewUsersPreviousMonth();

    @Query("SELECT u FROM User u WHERE u.personalTariffInfo.id = :tariffInfoId")
    Optional<User> findByPersonalTariffInfoId(@Param("tariffInfoId") String tariffInfoId);

    @Query("SELECT u.email FROM User u WHERE u.company.id = :company")
    List<String> emailsByCompany(@Param("company") String company);
}
