package repository

import (
	"context"
	"github.com/go-nunu/nunu-layout-advanced/internal/model"
)

type GameShieldSdkIpRepository interface {
	GetGameShieldSdkIp(ctx context.Context, id int64) (*model.GameShieldSdkIp, error)
	AddGameShieldSdkIp(ctx context.Context, req *model.GameShieldSdkIp) error
	UpdateGameShieldSdkIp(ctx context.Context, gameShieldSdkIp *model.GameShieldSdkIp) error
	DeleteGameShieldSdkIp(ctx context.Context, id int64) error
	GetGameShieldSdkIpByHostId(ctx context.Context, hostId int) (*model.GameShieldSdkIp, error)
	GetGameShieldSdkIpNewByHostId(ctx context.Context, hostId int) (string, error)
	GetGameShieldSdkIpCountByHostId(ctx context.Context, hostId int) (int64, error)
}

func NewGameShieldSdkIpRepository(
	repository *Repository,
) GameShieldSdkIpRepository {
	return &gameShieldSdkIpRepository{
		Repository: repository,
	}
}

type gameShieldSdkIpRepository struct {
	*Repository
}

func (r *gameShieldSdkIpRepository) GetGameShieldSdkIp(ctx context.Context, id int64) (*model.GameShieldSdkIp, error) {
	var res model.GameShieldSdkIp
	if err := r.DB(ctx).Where("id = ?", id).First(&res).Error; err != nil {
		return nil, err
	}
	return &res, nil
}

func (r *gameShieldSdkIpRepository) AddGameShieldSdkIp(ctx context.Context, req *model.GameShieldSdkIp) error {
	if err := r.DB(ctx).Create(req).Error; err != nil {
		return err
	}
	return nil
}

func (r *gameShieldSdkIpRepository) UpdateGameShieldSdkIp(ctx context.Context, gameShieldSdkIp *model.GameShieldSdkIp) error {
	if err := r.DB(ctx).Updates(gameShieldSdkIp).Error; err != nil {
		return err
	}
	return nil
}

func (r *gameShieldSdkIpRepository) DeleteGameShieldSdkIp(ctx context.Context, id int64) error {
	if err := r.DB(ctx).Where("id = ?", id).Delete(&model.GameShieldSdkIp{}).Error; err != nil {
		return err
	}
	return nil
}

func (r *gameShieldSdkIpRepository) GetGameShieldSdkIpByHostId(ctx context.Context, hostId int) (*model.GameShieldSdkIp, error) {
	var res model.GameShieldSdkIp
	if err := r.DB(ctx).Where("host_id = ?", hostId).Select(&model.GameShieldSdkIp{}).Error; err != nil {
		return nil, err
	}
	return &res, nil
}

func (r *gameShieldSdkIpRepository) GetGameShieldSdkIpNewByHostId(ctx context.Context, hostId int) (string, error) {
	var res model.GameShieldSdkIp
	if err := r.DB(ctx).Where("host_id = ?", hostId).Order("id DESC").First(&model.GameShieldSdkIp{}).Error; err != nil {
		return "", err
	}
	return res.SdkIp, nil
}

func (r *gameShieldSdkIpRepository) GetGameShieldSdkIpCountByHostId(ctx context.Context, hostId int) (int64, error) {
	var res int64
	if err := r.DB(ctx).Model(&model.GameShieldSdkIp{}).Where("host_id = ?", hostId).Count(&res).Error; err != nil {
		return 0, err
	}
	return res, nil
}
