package sy.edu.hiast.service;

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import sy.edu.hiast.model.Movie;
import sy.edu.hiast.model.User;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

@Service
public class DataGeneratorService {

    @Autowired
    private MongoTemplate mongoTemplate;
    private final Random random = new Random();

    public void runGeneration() {
        System.out.println("Starting data generation...");
        generateMovies(10000);
        generateUsers(5000);
        System.out.println("Generation complete!");
    }

    private void generateMovies(int count) {
        List<Movie> movies = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            Movie m = new Movie();
            m.setTitle(generateName());
            m.setRating(random.nextFloat() * 10.0f);
            m.setDirectors(Arrays.asList(generateName(), generateName()));
            movies.add(m);
            if (movies.size() >= 1000) { // Batch insert for speed
                mongoTemplate.insertAll(movies);
                movies.clear();
            }
        }
    }

    private void generateUsers(int count) {
        List<User> users = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            User u = new User();
            u.setUser_name("User_" + RandomStringUtils.randomAlphanumeric(5));
            u.setWatched_movies(Arrays.asList("Inside out", "Aladdin"));
            u.setSubscription_month(random.nextInt(12) + 1);
            users.add(u);
            if (users.size() >= 1000) {
                mongoTemplate.insertAll(users);
                users.clear();
            }
        }
    }

    private String generateName() {
        return RandomStringUtils.randomAlphabetic(1).toUpperCase() + 
               RandomStringUtils.randomAlphabetic(7).toLowerCase();
    }
}
