package com.example.volunteer.repository;

import com.example.volunteer.model.Event;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

/**
 * ============================================================================
 * (b) Repository — EventRepository
 * ============================================================================
 *
 * 【题目 / Question (b)】
 * EN — Write the JPA Repository code with the necessary JPA Queries (if any) to support the
 *      use case Display Events and their Volunteers.  (2 marks)
 * 中 — 写出支持“显示活动及其志愿者”页面的 JPA Repository 代码（如有需要，附上查询）。（2 分）
 *
 * 【判断 / Reasoning】
 * EN — The page starts from events, so only an EventRepository is required. The template
 *      will walk event -> signups -> volunteer, so both levels are fetched in one query to
 *      avoid LazyInitializationException. "left join" keeps events that have no sign-ups,
 *      and "distinct" removes the duplicated events produced by the join.
 * 中 — 页面从活动出发，只需要 EventRepository。模板要遍历 event → signups → volunteer，
 *      所以一次抓两层，避免模板渲染时惰性加载报错；用 left join 保留没有报名的活动，
 *      用 distinct 去掉 join 造成的重复活动。
 */
public interface EventRepository extends JpaRepository<Event, Long> {

    /**
     * EN — Fetch events together with their sign-ups and the volunteers of those sign-ups.
     * 中 — 一次取出活动、其报名记录、以及每条报名的志愿者。
     */
    @Query("select distinct e from Event e " +
           "left join fetch e.signups s " +
           "left join fetch s.volunteer")
    List<Event> findAllWithSignupsAndVolunteers();
}
