package main

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

	"juwan-backend/app/users/rpc/internal/models/schema"
	"juwan-backend/app/users/rpc/internal/models/users"
	"juwan-backend/app/users/rpc/internal/svc"
	"juwan-backend/common/utils/pwdUtils"
	"juwan-backend/pkg/types"

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

const adminUserID int64 = 100000

var adminVerifiedRoles = types.TextArray{
	Elements: []string{"consumer", "player", "owner", "admin"},
	Valid:    true,
}

var adminVerificationStatus = schema.VerificationStatusStruct{
	Consumer: "approved",
	Player:   "approved",
	Owner:    "approved",
}

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()
		var existing bool
		for i := range 30 {
			ok, 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
			}
			existing = ok
			break
		}

		if existing {
			err := svcCtx.UsersModelRW.Users.Update().
				Where(users.UsernameEQ(username)).
				SetIsAdmin(true).
				SetVerifiedRoles(adminVerifiedRoles).
				SetVerificationStatus(adminVerificationStatus).
				Exec(ctx)
			if err != nil {
				logx.Errorf("reconcile admin user: %v", err)
				return
			}
			logx.Infof("reconciled admin user: %s", username)
			return
		}

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

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

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