package user

import (
	"bytes"
	"context"
	"encoding/base64"
	"image/png"
	"strconv"
	"time"

	"bindbox-game/internal/repository/mysql/dao"
	"bindbox-game/internal/repository/mysql/model"

	randomname "github.com/DanPlayer/randomname"
	identicon "github.com/issue9/identicon/v2"
)

type LoginWeixinInput struct {
	OpenID     string
	UnionID    string
	Nickname   string
	AvatarURL  string
	InviteCode string
}

func (s *service) LoginWeixin(ctx context.Context, in LoginWeixinInput) (*model.Users, error) {
	var u *model.Users
	if in.OpenID != "" {
		u, _ = s.readDB.Users.WithContext(ctx).Where(s.readDB.Users.Openid.Eq(in.OpenID)).First()
	}
	if u == nil && in.UnionID != "" {
		u, _ = s.readDB.Users.WithContext(ctx).Where(s.readDB.Users.Unionid.Eq(in.UnionID)).First()
	}

	if u == nil {
		code := s.generateInviteCode(ctx)
		nickname := in.Nickname
		if nickname == "" {
			nickname = randomname.GenerateName()
		}
		avatar := in.AvatarURL
		if avatar == "" {
			seed := in.OpenID
			if seed == "" {
				seed = nickname
			}
			img := identicon.S2(128).Make([]byte(seed))
			var buf bytes.Buffer
			_ = png.Encode(&buf, img)
			avatar = "data:image/png;base64," + base64.StdEncoding.EncodeToString(buf.Bytes())
		}
		u = &model.Users{Nickname: nickname, Avatar: avatar, Openid: in.OpenID, Unionid: in.UnionID, InviteCode: code, Status: 1}
		if err := s.writeDB.Users.WithContext(ctx).Create(u); err != nil {
			return nil, err
		}
	} else {
		set := map[string]any{}
		if in.Nickname != "" {
			set["nickname"] = in.Nickname
		}
		if in.AvatarURL != "" {
			set["avatar"] = in.AvatarURL
		}
		if len(set) > 0 {
			if _, err := s.writeDB.Users.WithContext(ctx).Where(s.writeDB.Users.ID.Eq(u.ID)).Updates(set); err != nil {
				return nil, err
			}
			u, _ = s.readDB.Users.WithContext(ctx).Where(s.readDB.Users.ID.Eq(u.ID)).First()
		}
	}

	if in.InviteCode != "" {
		if err := s.writeDB.Transaction(func(tx *dao.Query) error {
			existed, _ := tx.UserInvites.WithContext(ctx).Where(tx.UserInvites.InviteeID.Eq(u.ID)).First()
			if existed != nil {
				return nil
			}
			inviter, _ := tx.Users.WithContext(ctx).Where(tx.Users.InviteCode.Eq(in.InviteCode)).First()
			if inviter == nil || inviter.ID == u.ID {
				return nil
			}
			reward := int64(10)
			inv := &model.UserInvites{InviterID: inviter.ID, InviteeID: u.ID, InviteCode: in.InviteCode, RewardPoints: reward, RewardedAt: time.Now()}
			if err := tx.UserInvites.WithContext(ctx).Create(inv); err != nil {
				return err
			}
			if u.InviterID == 0 {
				if _, err := tx.Users.WithContext(ctx).Where(tx.Users.ID.Eq(u.ID)).Updates(map[string]any{"inviter_id": inviter.ID}); err != nil {
					return err
				}
			}
			points, _ := tx.UserPoints.WithContext(ctx).Where(tx.UserPoints.UserID.Eq(inviter.ID)).Where(tx.UserPoints.Kind.Eq("invite")).First()
			if points == nil {
				points = &model.UserPoints{UserID: inviter.ID, Kind: "invite", Points: reward, ValidStart: time.Now()}
				do := tx.UserPoints.WithContext(ctx)
				if points.ValidEnd.IsZero() {
					do = do.Omit(tx.UserPoints.ValidEnd)
				}
				if err := do.Create(points); err != nil {
					return err
				}
			} else {
				if _, err := tx.UserPoints.WithContext(ctx).Where(tx.UserPoints.ID.Eq(points.ID)).Updates(map[string]any{"points": points.Points + reward}); err != nil {
					return err
				}
			}
			ledger := &model.UserPointsLedger{UserID: inviter.ID, Action: "invite_reward", Points: reward, RefTable: "user_invites", RefID: strconv.FormatInt(inv.ID, 10), Remark: "invite_reward"}
			if err := tx.UserPointsLedger.WithContext(ctx).Create(ledger); err != nil {
				return err
			}
			return nil
		}); err != nil {
			return nil, err
		}
	}

	return u, nil
}
