package com.example.volunteer.config;

import com.example.volunteer.model.Event;
import com.example.volunteer.model.Signup;
import com.example.volunteer.model.Volunteer;
import com.example.volunteer.repository.EventRepository;
import com.example.volunteer.repository.VolunteerRepository;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDate;
import java.util.List;

/**
 * ============================================================================
 * 示例数据 / Sample data（不属于考试要求）
 * ============================================================================
 *
 * EN — Creates two events, three volunteers and a few sign-ups so that the page and the API
 *      can be demonstrated immediately after start-up.
 * 中 — 启动时写入两个活动、三个志愿者和几条报名，方便直接看页面 / 调接口。
 */
@Configuration
public class DataInitializer {

    @Bean
    CommandLineRunner seed(EventRepository eventRepository, VolunteerRepository volunteerRepository) {
        return args -> {
            Event beach = new Event("Beach Cleanup", LocalDate.now().plusDays(3), "East Coast Park", 10);
            Event teach = new Event("Teach Seniors Smartphone", LocalDate.now().plusDays(10), "Tampines Hub", 8);

            Volunteer alice = new Volunteer("Alice Tan", "alice@example.com", "91234567");
            Volunteer bob = new Volunteer("Bob Lim", "bob@example.com", "92345678");
            Volunteer cara = new Volunteer("Cara Ng", "cara@example.com", "93456789");

            beach.addSignup(new Signup(alice, LocalDate.now(), 4));
            beach.addSignup(new Signup(bob, LocalDate.now(), 3));
            teach.addSignup(new Signup(alice, LocalDate.now(), 2));

            // 先存志愿者（拿到 id 并纳入持久化上下文），再存活动；
            // 否则 Event 级联保存 Signup 时，Signup 引用的 Volunteer 还是 transient，会报
            // TransientPropertyValueException / object references an unsaved transient instance
            volunteerRepository.saveAll(List.of(alice, bob, cara));
            eventRepository.saveAll(List.of(beach, teach));
        };
    }
}
