package com.alttd.altitudeweb.mappers;

import com.alttd.altitudeweb.database.web_db.forms.StaffApplication;
import com.alttd.altitudeweb.model.StaffApplicationDto;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class StaffApplicationDataMapper {

    /**
     * Maps the incoming DTO and the authenticated user's UUID to a StaffApplication entity.
     * Normalizes and prepares fields as needed (lowercase email, join availableDays, timestamps, ids).
     */
    public StaffApplication map(UUID userUuid, StaffApplicationDto dto) {
        String email = dto.getEmail() == null ? null : dto.getEmail().toLowerCase();
        String availableDaysJoined = joinList(dto.getAvailableDays());

        return new StaffApplication(
                UUID.randomUUID(),
                userUuid,
                email,
                dto.getAge(),
                dto.getDiscordUsername(),
                Boolean.TRUE.equals(dto.getMeetsRequirements()),
                dto.getPronouns(),
                dto.getJoinDate(),
                dto.getWeeklyPlaytime(),
                availableDaysJoined,
                dto.getAvailableTimes(),
                dto.getPreviousExperience(),
                dto.getPluginExperience(),
                dto.getModeratorExpectations(),
                dto.getAdditionalInfo(),
                Instant.now(),
                null,
                null
        );
    }

    private String joinList(List<String> list) {
        if (list == null) return null;
        // Avoid NPEs and trim entries
        return list.stream()
                .filter(s -> s != null && !s.isBlank())
                .map(String::trim)
                .collect(Collectors.joining(","));
    }
}
