package admin

import (
	"context"
	"fmt"
	"time"

	"bindbox-game/internal/pkg/utils"
	"bindbox-game/internal/repository/mysql/model"

	"gorm.io/gorm"
)

type CreateInput struct {
	Username  string
	Nickname  string
	Mobile    string
	Password  string
	Avatar    string
	CreatedBy string
}

func (s *service) Create(ctx context.Context, in CreateInput) error {
	info, err := s.readDB.Admin.WithContext(ctx).
		Where(s.readDB.Admin.Username.Eq(in.Username)).
		First()
	if err != nil && err != gorm.ErrRecordNotFound {
		return err
	}
	if info != nil {
		return fmt.Errorf("该账号已存在")
	}

	hashedPassword, err := utils.GenerateAdminHashedPassword(in.Password)
	if err != nil {
		return err
	}

	admin := &model.Admin{
		Username:    in.Username,
		Nickname:    in.Nickname,
		Mobile:      in.Mobile,
		Password:    hashedPassword,
		Avatar:      in.Avatar,
		LoginStatus: 1,
		IsSuper:     0,
		CreatedUser: in.CreatedBy,
		CreatedAt:   time.Now(),
	}
	return s.writeDB.Admin.WithContext(ctx).Create(admin)
}
