package de.assecutor.votianlt.repository;

import de.assecutor.votianlt.model.JobHistory;
import de.assecutor.votianlt.model.JobHistoryType;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;

@Repository
public interface JobHistoryRepository extends MongoRepository<JobHistory, ObjectId> {

    /**
     * Find all history entries for a specific job, ordered by timestamp descending
     * (newest first)
     */
    List<JobHistory> findByJobIdOrderByTimestampDesc(ObjectId jobId);

    /**
     * Find all history entries for a specific job, ordered by timestamp ascending
     * (oldest first)
     */
    List<JobHistory> findByJobIdOrderByTimestampAsc(ObjectId jobId);

    /**
     * Find history entries for a job within a specific time range
     */
    List<JobHistory> findByJobIdAndTimestampBetweenOrderByTimestampDesc(ObjectId jobId, LocalDateTime start,
            LocalDateTime end);

    /**
     * Find history entries by change type for a specific job
     */
    List<JobHistory> findByJobIdAndChangeTypeOrderByTimestampDesc(ObjectId jobId, JobHistoryType changeType);

    /**
     * Find history entries made by a specific user
     */
    List<JobHistory> findByChangedByOrderByTimestampDesc(String changedBy);

    /**
     * Find recent history entries across all jobs (for dashboard/overview)
     */
    @Query(value = "{}", sort = "{ 'timestamp' : -1 }")
    List<JobHistory> findRecentHistoryEntries();

    /**
     * Count history entries for a specific job
     */
    long countByJobId(ObjectId jobId);

    /**
     * Find the latest history entry for a specific job
     */
    @Query(value = "{'jobId': ?0}", sort = "{ 'timestamp' : -1 }")
    JobHistory findLatestByJobId(ObjectId jobId);

    /**
     * Delete all history entries for a specific job
     */
    void deleteByJobId(ObjectId jobId);
}