package repository

import (
	"context"

	dbgen "github.com/SamuelTariku/FortuneBet-Backend/gen/db"
	"github.com/SamuelTariku/FortuneBet-Backend/internal/domain"
	"github.com/jackc/pgx/v5/pgtype"
)

func (s *Store) SaveLeague(ctx context.Context, l domain.League) error {
	return s.queries.InsertLeague(ctx, dbgen.InsertLeagueParams{
		ID:          l.ID,
		Name:        l.Name,
		CountryCode: pgtype.Text{String: l.CountryCode, Valid: true},
		Bet365ID:    pgtype.Int4{Int32: l.Bet365ID, Valid: true},
		IsActive:    pgtype.Bool{Bool: l.IsActive, Valid: true},
		SportID:     l.SportID,
	})
}

func (s *Store) GetAllLeagues(ctx context.Context, filter domain.LeagueFilter) ([]domain.League, error) {
	l, err := s.queries.GetAllLeagues(ctx, dbgen.GetAllLeaguesParams{
		CountryCode: pgtype.Text{
			String: filter.CountryCode.Value,
			Valid:  filter.CountryCode.Valid,
		},
		SportID: pgtype.Int4{
			Int32: filter.SportID.Value,
			Valid: filter.SportID.Valid,
		},
		IsActive: pgtype.Bool{
			Bool:  filter.IsActive.Value,
			Valid: filter.IsActive.Valid,
		},
		Limit: pgtype.Int4{
			Int32: int32(filter.Limit.Value),
			Valid: filter.Limit.Valid,
		},
		Offset: pgtype.Int4{
			Int32: int32(filter.Offset.Value * filter.Limit.Value),
			Valid: filter.Offset.Valid,
		},
	})
	if err != nil {
		return nil, err
	}

	leagues := make([]domain.League, len(l))
	for i, league := range l {
		leagues[i] = domain.League{
			ID:          league.ID,
			Name:        league.Name,
			CountryCode: league.CountryCode.String,
			Bet365ID:    league.Bet365ID.Int32,
			IsActive:    league.IsActive.Bool,
			SportID:     league.SportID,
		}
	}
	return leagues, nil
}

func (s *Store) CheckLeagueSupport(ctx context.Context, leagueID int64) (bool, error) {
	return s.queries.CheckLeagueSupport(ctx, leagueID)
}

func (s *Store) SetLeagueActive(ctx context.Context, leagueId int64, isActive bool) error {
	return s.queries.SetLeagueActive(ctx, dbgen.SetLeagueActiveParams{
		ID: leagueId,
		IsActive: pgtype.Bool{
			Bool:  isActive,
			Valid: true,
		},
	})
}

func (s *Store) UpdateLeague(ctx context.Context, league domain.UpdateLeague) error {
	err := s.queries.UpdateLeague(ctx, dbgen.UpdateLeagueParams{
		ID: league.ID,
		Name: pgtype.Text{
			String: league.Name.Value,
			Valid:  league.Name.Valid,
		},
		CountryCode: pgtype.Text{
			String: league.CountryCode.Value,
			Valid:  league.CountryCode.Valid,
		},
		Bet365ID: pgtype.Int4{
			Int32: league.Bet365ID.Value,
			Valid: league.Bet365ID.Valid,
		},
		IsActive: pgtype.Bool{
			Bool:  league.IsActive.Value,
			Valid: league.IsActive.Valid,
		},
		SportID: pgtype.Int4{
			Int32: league.SportID.Value,
			Valid: league.SportID.Valid,
		},
	})

	return err
}
