package kr.co.accura.wtm.domain.wbs.repository;

import kr.co.accura.wtm.domain.wbs.entity.WbsVersion;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

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

@Repository
public interface WbsVersionRepository extends JpaRepository<WbsVersion, Long> {

    List<WbsVersion> findByProject_IdOrderByVersionNumberDesc(Long projectId);

    @Query("SELECT MAX(v.versionNumber) FROM WbsVersion v WHERE v.project.id = :projectId")
    Optional<Integer> findMaxVersionByProjectId(@Param("projectId") Long projectId);

    @Modifying
    @Query("UPDATE WbsVersion v SET v.status = 'ARCHIVED' WHERE v.project.id = :projectId AND v.status = 'ACTIVE'")
    void archiveActiveVersions(@Param("projectId") Long projectId);

    Optional<WbsVersion> findByProject_IdAndVersionNumber(Long projectId, Integer versionNumber);
}
