package teams_repo

import (
	"context"
	"evening_detective_server/internal/repos"

	"github.com/jackc/pgx/v5/pgxpool"
)

type TeamsRepo struct {
	pool *pgxpool.Pool
}

func NewTeamsRepo(pool *pgxpool.Pool) *TeamsRepo {
	return &TeamsRepo{
		pool: pool,
	}
}

func (r *TeamsRepo) GetTeamsByGameID(
	ctx context.Context,
	gameId int,
) ([]*repos.Team, error) {
	rows, err := r.pool.Query(
		ctx,
		`SELECT 
			scenarios.id, 
			scenarios.name, 
			scenarios.description, 
			scenarios.image, 
			scenarios.scenario, 
			users.id, 
			users.username, 
			scenarios.status, 
			scenarios.updated_at, 
			scenarios.created_at, 
			scenarios.published_at
		FROM scenarios
		LEFT JOIN users on scenarios.author_id = users.id
		WHERE scenarios.author_id = $1 and is_deleted = FALSE
		ORDER BY created_at DESC`,
		gameId,
	)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var teams []*repos.Team
	for rows.Next() {
		team := &repos.Team{}
		err := rows.Scan(
			&team.ID,
			&team.Name,
			&team.Password,
		)
		if err != nil {
			return nil, err
		}
		teams = append(teams, team)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}

	return teams, nil
}
