package auth

import (
	"context"
	"fmt"
	"strings"
	"time"

	"github.com/perfect-panel/server/internal/config"
	"github.com/perfect-panel/server/internal/model/log"
	"github.com/perfect-panel/server/internal/model/user"
	"github.com/perfect-panel/server/internal/svc"
	"github.com/perfect-panel/server/internal/types"
	"github.com/perfect-panel/server/pkg/constant"
	"github.com/perfect-panel/server/pkg/jwt"
	"github.com/perfect-panel/server/pkg/logger"
	"github.com/perfect-panel/server/pkg/tool"
	"github.com/perfect-panel/server/pkg/uuidx"
	"github.com/perfect-panel/server/pkg/xerr"
	"github.com/pkg/errors"
	"gorm.io/gorm"
)

type EmailLoginLogic struct {
	logger.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewEmailLoginLogic Email verify code login
func NewEmailLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *EmailLoginLogic {
	return &EmailLoginLogic{
		Logger: logger.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *EmailLoginLogic) EmailLogin(req *types.EmailLoginRequest) (resp *types.LoginResponse, err error) {
	loginStatus := false
	var userInfo *user.User
	var isNewUser bool

	req.Email = strings.ToLower(strings.TrimSpace(req.Email))
	req.Code = strings.TrimSpace(req.Code)

	// Verify Code

	// Check User
	userInfo, err = l.svcCtx.UserModel.FindOneByEmail(l.ctx, req.Email)
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseQueryError), "query user info failed: %v", err.Error())
	}

	if userInfo == nil || errors.Is(err, gorm.ErrRecordNotFound) {
		// Auto Register
		isNewUser = true
		c := l.svcCtx.Config.Register
		if c.StopRegister {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.StopRegister), "user not found and registration is stopped")
		}

		var referer *user.User
		if req.Invite == "" {
			if l.svcCtx.Config.Invite.ForcedInvite {
				return nil, errors.Wrapf(xerr.NewErrCode(xerr.InviteCodeError), "invite code is required for new user")
			}
		} else {
			referer, err = l.svcCtx.UserModel.FindOneByReferCode(l.ctx, req.Invite)
			if err != nil {
				return nil, errors.Wrapf(xerr.NewErrCode(xerr.InviteCodeError), "invite code is invalid")
			}
		}

		// Create User
		pwd := tool.EncodePassWord(uuidx.NewUUID().String())
		userInfo = &user.User{
			Password:          pwd,
			Algo:              "default",
			OnlyFirstPurchase: &l.svcCtx.Config.Invite.OnlyFirstPurchase,
		}
		if referer != nil {
			userInfo.RefererId = referer.Id
		}

		err = l.svcCtx.UserModel.Transaction(l.ctx, func(db *gorm.DB) error {
			if err := db.Create(userInfo).Error; err != nil {
				return err
			}
			userInfo.ReferCode = uuidx.UserInviteCode(userInfo.Id)
			if err := db.Model(&user.User{}).Where("id = ?", userInfo.Id).Update("refer_code", userInfo.ReferCode).Error; err != nil {
				return err
			}
			authInfo := &user.AuthMethods{
				UserId:         userInfo.Id,
				AuthType:       "email",
				AuthIdentifier: req.Email,
				Verified:       true,
			}
			if err = db.Create(authInfo).Error; err != nil {
				return err
			}
			rc := l.svcCtx.Config.Register
			if ShouldAutoGrantTrialOnPublicEmailFlows(rc) &&
				ShouldGrantTrialForEmail(rc, req.Email) &&
				!NormalizedEmailHasTrial(l.ctx, l.svcCtx.DB, req.Email, rc.TrialSubscribe) {
				if err = l.activeTrial(userInfo.Id); err != nil {
					return err
				}
			}
			return nil
		})
		if err != nil {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DatabaseUpdateError), "register failed: %v", err.Error())
		}
	}

	// Record login status
	defer func() {
		if userInfo.Id != 0 {
			loginLog := log.Login{
				Method:    "email_code",
				LoginIP:   req.IP,
				UserAgent: req.UserAgent,
				Success:   loginStatus,
				Timestamp: time.Now().UnixMilli(),
			}
			content, _ := loginLog.Marshal()
			l.svcCtx.LogModel.Insert(l.ctx, &log.SystemLog{
				Type:     log.TypeLogin.Uint8(),
				Date:     time.Now().Format("2006-01-02"),
				ObjectID: userInfo.Id,
				Content:  string(content),
			})

			if isNewUser {
				registerLog := log.Register{
					AuthMethod: "email_code",
					Identifier: req.Email,
					RegisterIP: req.IP,
					UserAgent:  req.UserAgent,
					Timestamp:  time.Now().UnixMilli(),
				}
				regContent, _ := registerLog.Marshal()
				l.svcCtx.LogModel.Insert(l.ctx, &log.SystemLog{
					Type:     log.TypeRegister.Uint8(),
					ObjectID: userInfo.Id,
					Date:     time.Now().Format("2006-01-02"),
					Content:  string(regContent),
				})
			}
		}
	}()

	// Update last login time
	now := time.Now()
	userInfo.LastLoginTime = &now
	if err := l.svcCtx.UserModel.Update(l.ctx, userInfo); err != nil {
		l.Errorw("failed to update last login time",
			logger.Field("user_id", userInfo.Id),
			logger.Field("error", err.Error()),
		)
	}

	// Login type from context
	if l.ctx.Value(constant.LoginType) != nil {
		req.LoginType = l.ctx.Value(constant.LoginType).(string)
	}

	// Generate session and token
	sessionId := uuidx.NewUUID().String()

	token, err := jwt.NewJwtToken(
		l.svcCtx.Config.JwtAuth.AccessSecret,
		time.Now().Unix(),
		l.svcCtx.Config.JwtAuth.AccessExpire,
		jwt.WithOption("UserId", userInfo.Id),
		jwt.WithOption("SessionId", sessionId),
		jwt.WithOption("CtxLoginType", req.LoginType),
		jwt.WithOption("LoginType", req.LoginType),
	)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "token generate error: %v", err.Error())
	}

	// Store session in redis
	sessionIdCacheKey := fmt.Sprintf("%v:%v", config.SessionIdKey, sessionId)
	if err = l.svcCtx.Redis.Set(l.ctx, sessionIdCacheKey, userInfo.Id, time.Duration(l.svcCtx.Config.JwtAuth.AccessExpire)*time.Second).Err(); err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.ERROR), "set session id error: %v", err.Error())
	}

	loginStatus = true
	return &types.LoginResponse{
		Token: token,
	}, nil
}

// activeTrial activates trial subscription for new user
func (l *EmailLoginLogic) activeTrial(uid int64) error {
	sub, err := l.svcCtx.SubscribeModel.FindOne(l.ctx, l.svcCtx.Config.Register.TrialSubscribe)
	if err != nil {
		return err
	}
	userSub := &user.Subscribe{
		UserId:      uid,
		OrderId:     0,
		SubscribeId: sub.Id,
		StartTime:   time.Now(),
		ExpireTime:  tool.AddTime(l.svcCtx.Config.Register.TrialTimeUnit, l.svcCtx.Config.Register.TrialTime, time.Now()),
		Traffic:     sub.Traffic,
		Download:    0,
		Upload:      0,
		Token:       uuidx.NewUUID().String(),
		UUID:        uuidx.NewUUID().String(),
		Status:      1,
	}
	err = l.svcCtx.UserModel.InsertSubscribe(l.ctx, userSub)
	if err != nil {
		return err
	}
	if clearErr := l.svcCtx.NodeModel.ClearServerAllCache(l.ctx); clearErr != nil {
		l.Errorf("ClearServerAllCache error: %v", clearErr.Error())
	}
	return err
}
