package game_service

import (
	"context"
	"evening_detective_server/internal/repos/games_repo"
	"evening_detective_server/internal/repos/scenarios_repo"
	"evening_detective_server/internal/repos/teams_repo"
	"time"
)

type GameService struct {
	gamesRepo     *games_repo.GamesRepo
	teamsRepo     *teams_repo.TeamsRepo
	scenariosRepo *scenarios_repo.ScenariosRepo
	domain        string
}

func NewGameService(
	gamesRepo *games_repo.GamesRepo,
	teamsRepo *teams_repo.TeamsRepo,
	scenariosRepo *scenarios_repo.ScenariosRepo,
	domain string,
) *GameService {
	return &GameService{
		gamesRepo:     gamesRepo,
		teamsRepo:     teamsRepo,
		scenariosRepo: scenariosRepo,
		domain:        domain,
	}
}

func (s *GameService) AddGame(
	ctx context.Context,
	name string,
	description string,
	startAt time.Time,
	scenarioId int32,
) (int, error) {
	id, err := s.gamesRepo.AddGame(ctx, name, description, startAt, scenarioId)
	if err != nil {
		return 0, err
	}
	return id, nil
}

func (s *GameService) GetGame(
	ctx context.Context,
	id int,
) (*Game, error) {
	game, err := s.gamesRepo.GetGameByID(ctx, id)
	if err != nil {
		return nil, err
	}
	scenario, err := s.scenariosRepo.GetScenarioByID(ctx, game.ScenarioId)
	if err != nil {
		return nil, err
	}
	game.Scenario = scenario
	teams, err := s.teamsRepo.GetTeamsByGameID(ctx, id)
	if err != nil {
		return nil, err
	}
	game.Teams = teams
	return mapGame(game, s.domain), nil
}

func (s *GameService) DeleteGame(
	ctx context.Context,
	id int,
) error {
	return s.gamesRepo.DeleteGameByID(ctx, id)
}

func (s *GameService) GetGames(
	ctx context.Context,
) ([]*Game, error) {
	games, err := s.gamesRepo.GetGames(ctx)
	if err != nil {
		return nil, err
	}
	return mapGames(games, s.domain), nil
}

func (s *GameService) UpdateGame(
	ctx context.Context,
	id int,
	name string,
	description string,
	startAt time.Time,
	scenarioId int32,
) error {
	return s.gamesRepo.UpdateGame(ctx, id, name, description, startAt, scenarioId)
}
