package db

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"youngee_b_api/model/gorm_model"
)

func CreateUser(ctx context.Context, user gorm_model.YounggeeUser) (*int64, error) {
	db := GetReadDB(ctx)
	err := db.Create(&user).Error
	if err != nil {
		return nil, err
	}
	return &user.ID, nil
}

// GetUserByPhone 查不到返回空 根据手机号在User表中查服务商用户数据
func GetUserByPhone(ctx context.Context, phone string) (*gorm_model.YounggeeUser, error) {
	db := GetReadDB(ctx)
	user := &gorm_model.YounggeeUser{}
	err := db.Model(user).Where("phone = ? AND role = 6", phone).First(user).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			fmt.Println("record not found")
			return nil, nil
		}
		return nil, err
	}
	return user, nil
}

// GetSubUserByPhone 根据手机号在user表中查找子账号用户
func GetSubUserByPhone(ctx context.Context, phone string) (*gorm_model.YounggeeUser, error) {
	db := GetReadDB(ctx)
	user := &gorm_model.YounggeeUser{}
	err := db.Model(user).Where("phone = ? AND role = 7", phone).First(user).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			fmt.Println("record not found")
			return nil, nil
		}
		return nil, err
	}
	return user, nil
}

// GetUserByID 查不到返回空
func GetUserByID(ctx context.Context, ID int64) (*gorm_model.YounggeeUser, error) {
	db := GetReadDB(ctx)
	user := &gorm_model.YounggeeUser{}
	err := db.Model(user).Where("id = ?", ID).First(user).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			fmt.Println("record not found")
			return nil, nil
		}
		return nil, err
	}
	return user, nil
}

func UpdateUser(ctx context.Context, UserID int64, UserName string, Email string) (*int64, error) {
	db := GetReadDB(ctx)
	user := &gorm_model.YounggeeUser{}
	err := db.Model(user).Where("id = ?", UserID).Updates(map[string]interface{}{"UserName": UserName, "Email": Email}).Error
	if err != nil {
		fmt.Println("Update User Failed!")
		return nil, err
	}
	return &UserID, nil
}
