package db

import (
	"context"
	"github.com/issue9/conv"
	"gorm.io/gorm"
	"youngee_b_api/model/gorm_model"
)

func CreateIncome(ctx context.Context, income gorm_model.YounggeeTalentIncome, tx *gorm.DB) error {
	if tx != nil {
		err := tx.Create(&income).Error
		if err != nil {
			return err
		}
		err = tx.Model(gorm_model.YoungeeTalentInfo{}).Where("id = ?", income.TalentID).Updates(map[string]interface{}{"income": gorm.Expr("income + ?", conv.MustFloat64(income.Income)), "canwithdraw": gorm.Expr("canwithdraw + ?", conv.MustFloat64(income.Income))}).Error
		if err != nil {
			return err
		}
	} else {
		db := GetWriteDB(ctx)
		err := db.Create(&income).Error
		if err != nil {
			return err
		}
		err = db.Model(gorm_model.YoungeeTalentInfo{}).Where("id = ?", income.TalentID).Updates(map[string]interface{}{"income": gorm.Expr("income + ?", conv.MustFloat64(income.Income)), "canwithdraw": gorm.Expr("canwithdraw + ?", conv.MustFloat64(income.Income))}).Error
		if err != nil {
			return err
		}
	}
	return nil
}
