package de.votian.services.repository;

import de.votian.services.entity.Parameter;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
import java.util.Optional;

public interface ParameterRepository extends JpaRepository<Parameter, Long> {

    @Query("SELECT p FROM Parameter p WHERE p.key = :key AND p.headquartersId = :hqId AND p.employeeId = :empId")
    Optional<Parameter> findByKeyAndHqAndEmployee(@Param("key") String key, @Param("hqId") Long hqId, @Param("empId") Long empId);

    @Query("SELECT p FROM Parameter p WHERE p.key = :key ORDER BY p.headquartersId")
    List<Parameter> findByKeyOrderByHq(@Param("key") String key);

    List<Parameter> findByKey(String key);

    /**
     * Bulk-load all global parameters for a given headquarters (emp_id = 0).
     * Equivalent to PHP defineGlobalParameters().
     */
    @Query("SELECT p FROM Parameter p WHERE p.employeeId = 0 AND p.headquartersId = :hqId")
    List<Parameter> findGlobalByHq(@Param("hqId") Long hqId);

    /**
     * Bulk-load all parameters for a given headquarters (all employees).
     */
    @Query("SELECT p FROM Parameter p WHERE p.headquartersId = :hqId")
    List<Parameter> findAllByHq(@Param("hqId") Long hqId);

    /**
     * Bulk-load all parameters for a given employee within a headquarters.
     */
    @Query("SELECT p FROM Parameter p WHERE p.headquartersId = :hqId AND p.employeeId = :empId")
    List<Parameter> findAllByHqAndEmployee(@Param("hqId") Long hqId, @Param("empId") Long empId);

    /**
     * Find parameters by key prefix (for dynamic keys like CUSTOMER_MASK_JOBLIST_FIELDS_123456).
     */
    @Query("SELECT p FROM Parameter p WHERE p.key LIKE CONCAT(:keyPrefix, '%') AND p.headquartersId = :hqId")
    List<Parameter> findByKeyPrefixAndHq(@Param("keyPrefix") String keyPrefix, @Param("hqId") Long hqId);

    /**
     * Find parameters by key prefix across all headquarters.
     */
    @Query("SELECT p FROM Parameter p WHERE p.key LIKE CONCAT(:keyPrefix, '%')")
    List<Parameter> findByKeyPrefix(@Param("keyPrefix") String keyPrefix);
}
