package com.alttd.altitudeweb.database.litebans;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.ArrayList;
import java.util.List;

public interface RecentNamesMapper {

    @Select("""
            SELECT DISTINCT name AS username
            FROM litebans_history
            WHERE uuid = #{uuid}
            ORDER BY date DESC
            LIMIT 1;
            """)
    String getUsername(@Param("uuid") String uuid);


    @Select("""
            SELECT DISTINCT user_lookup.name AS punished_name
            FROM ${tableName} AS punishment
            INNER JOIN user_lookup
                ON user_lookup.uuid = punishment.${uuid_column}
            WHERE punishment.time > UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 YEAR)) * 1000
            ORDER BY user_lookup.name
            """)
    List<String> getRecentHistory(@Param("tableName") String tableName, @Param("uuid_column") String uuidColumn);

    default List<String> getRecent(HistoryType historyType, UserType userType) {
        return switch (historyType) {
            case ALL -> getRecentAll(userType);
            case BAN -> getRecentBans(userType);
            case MUTE -> getRecentMutes(userType);
            case KICK -> getRecentKicks(userType);
            case WARN -> getRecentWarns(userType);
        };
    }

    private List<String> getRecent(String tableName, UserType userType) {
        switch (userType) {
            case PLAYER -> {
                return getRecentHistory(tableName, "uuid");
            }
            case STAFF -> {
                return getRecentHistory(tableName, "banned_by_uuid");
            }
            default -> throw new IllegalArgumentException("Invalid user type");
        }
    }

    private List<String> getRecentBans(UserType userType) {
        return getRecent("litebans_bans", userType);
    }

    private List<String> getRecentKicks(UserType userType) {
        return getRecent("litebans_kicks", userType);
    }

    private List<String> getRecentMutes(UserType userType) {
        return getRecent("litebans_mutes", userType);
    }

    private List<String> getRecentWarns(UserType userType) {
        return getRecent("litebans_warnings", userType);
    }

    private List<String> getRecentAll(UserType userType) {
        List<String> all = new ArrayList<>();
        all.addAll(getRecentBans(userType));
        // Removed recent kicks as we do not show those
//        all.addAll(getRecentKicks(userType));
        all.addAll(getRecentMutes(userType));
        all.addAll(getRecentWarns(userType));
        return all;
    }

}
