package main

import (
	"context"
	"os"
	"strings"
	"time"

	"juwan-backend/app/snowflake/rpc/snowflake"
	"juwan-backend/app/users/rpc/internal/models/users"
	"juwan-backend/app/users/rpc/internal/svc"
	"juwan-backend/common/utils/pwdUtils"

	"github.com/zeromicro/go-zero/core/logx"
)

func initAdmin(svcCtx *svc.ServiceContext) {
	username := strings.TrimSpace(os.Getenv("ADMIN_USERNAME"))
	password := strings.TrimSpace(os.Getenv("ADMIN_PASSWORD"))
	email := strings.TrimSpace(os.Getenv("ADMIN_EMAIL"))
	if username == "" || password == "" || email == "" {
		return
	}

	go func() {
		ctx := context.Background()
		for i := range 30 {
			exists, err := svcCtx.UsersModelRW.Users.Query().Where(users.UsernameEQ(username)).Exist(ctx)
			if err != nil {
				if i < 29 {
					time.Sleep(time.Second)
					continue
				}
				logx.Errorf("check admin user: %v", err)
				return
			}
			if exists {
				return
			}
			break
		}

		hashedPassword, err := pwdUtils.HashPassword(password)
		if err != nil {
			logx.Errorf("hash admin password: %v", err)
			return
		}

		resp, err := svcCtx.Snowflake.NextId(ctx, &snowflake.NextIdReq{})
		if err != nil {
			logx.Errorf("generate admin user ID: %v", err)
			return
		}

		_, err = svcCtx.UsersModelRW.Users.Create().
			SetID(resp.Id).
			SetUsername(username).
			SetPasswordHash(hashedPassword).
			SetEmail(email).
			SetPhone("").
			SetBio("").
			SetAvatar("").
			SetCurrentRole("consumer").
			SetNickname(username).
			SetIsAdmin(true).
			Save(ctx)
		if err != nil {
			logx.Errorf("create admin user: %v", err)
			return
		}

		logx.Infof("initialized admin user: %s", username)
	}()
}
