package database

import (
	"context"

	"gitea.mrixs.me/minecraft-platform/backend/internal/models"
	"github.com/jackc/pgx/v5/pgxpool"
)

type ServerRepository struct {
	DB *pgxpool.Pool
}

// GetAllEnabledServers возвращает все активные серверы для опроса.
func (r *ServerRepository) GetAllEnabledServers(ctx context.Context) ([]*models.GameServer, error) {
	rows, err := r.DB.Query(ctx, "SELECT id, name, address FROM game_servers WHERE is_enabled = TRUE")
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var servers []*models.GameServer
	for rows.Next() {
		s := &models.GameServer{}
		if err := rows.Scan(&s.ID, &s.Name, &s.Address); err != nil {
			return nil, err
		}
		servers = append(servers, s)
	}
	return servers, nil
}

// UpdateServerStatus обновляет данные о статусе сервера.
func (r *ServerRepository) UpdateServerStatus(ctx context.Context, id int, status *models.ServerStatus) error {
	query := `
		UPDATE game_servers SET
		status_json = $1, last_polled_at = NOW(), motd = $2, player_count = $3,
		max_players = $4, version_name = $5, ping_backend_server = $6
		WHERE id = $7`
	_, err := r.DB.Exec(ctx, query,
		status.StatusJSON, status.Motd, status.PlayerCount, status.MaxPlayers,
		status.VersionName, status.Ping, id)
	return err
}

// GetAllWithStatus возвращает все активные серверы с их текущим статусом.
func (r *ServerRepository) GetAllWithStatus(ctx context.Context) ([]*models.GameServer, error) {
	query := `
		SELECT id, name, address, is_enabled, last_polled_at, motd,
		player_count, max_players, version_name, ping_backend_server, bluemap_url
		FROM game_servers WHERE is_enabled = TRUE ORDER BY name`
	rows, err := r.DB.Query(ctx, query)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var servers []*models.GameServer
	for rows.Next() {
		s := &models.GameServer{}
		if err := rows.Scan(&s.ID, &s.Name, &s.Address, &s.IsEnabled, &s.LastPolledAt,
			&s.Motd, &s.PlayerCount, &s.MaxPlayers, &s.VersionName, &s.PingBackendServer, &s.BlueMapURL); err != nil {
			return nil, err
		}
		servers = append(servers, s)
	}
	return servers, nil
}
