package db

import (
	"context"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
	"youngee_b_api/model/gorm_model"
)

func CreateRecruitStrategy(ctx context.Context, recruitStrategys []gorm_model.RecruitStrategy) error {
	db := GetReadDB(ctx)
	err := db.Create(&recruitStrategys).Error
	if err != nil {
		return err
	}
	return nil
}

func DeleteRecruitStrategyByProjectID(ctx context.Context, projectID string) error {
	db := GetReadDB(ctx)
	err := db.Where("project_id = ?", projectID).Delete(&gorm_model.RecruitStrategy{}).Error
	if err != nil {
		return err
	}
	return nil
}

func CalculateSelectedNumberByRecruitStrategyID(ctx context.Context, recruitstrategyID int64, AddNumber int64) error {
	db := GetReadDB(ctx)
	err := db.Model(gorm_model.RecruitStrategy{}).Where("recruit_strategy_id = ?", recruitstrategyID).
		Updates(map[string]interface{}{"selected_number": gorm.Expr("selected_number + ?", AddNumber), "waiting_number": gorm.Expr("waiting_number + ?", AddNumber)}).Error
	if err != nil {
		return err
	}
	return nil
}

func UpdateLogisticsNumber(ctx context.Context, RecruitStrategyID int64, delivered_value int64, waiting_value int64, signed_value int64) error {
	db := GetReadDB(ctx)
	err := db.Model(gorm_model.RecruitStrategy{}).Where("recruit_strategy_id = ?", RecruitStrategyID).
		Updates(map[string]interface{}{"delivered_number": gorm.Expr("delivered_number + ?", delivered_value), "waiting_number": gorm.Expr("waiting_number + ?", waiting_value), "signed_number": gorm.Expr("signed_number + ?", signed_value)}).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[logistics db] call CreateLogistics error,err:%+v", err)
		return err
	}
	return nil
}

func GetRecruitStrategyIdByTS(ctx context.Context, projectId string, strategyID int64) (*int64, error) {
	db := GetReadDB(ctx)
	RecruitStrategy := &gorm_model.RecruitStrategy{}
	err := db.Model(gorm_model.RecruitStrategy{}).Where("project_id = ? AND strategy_id = ?", projectId, strategyID).Scan(RecruitStrategy).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[logistics db] call GetRecruitStrategyIdByTS error,err:%+v", err)
		return nil, err
	}
	return &RecruitStrategy.RecruitStrategyID, nil
}

func GetRecruitStrategyByProjectId(ctx context.Context, projectId string) ([]gorm_model.RecruitStrategy, error) {
	db := GetReadDB(ctx)
	RecruitStrategys := []gorm_model.RecruitStrategy{}
	err := db.Model(gorm_model.RecruitStrategy{}).Where("project_id = ? AND strategy_type = ?", projectId, 1).Scan(&RecruitStrategys).Error
	if err != nil {
		logrus.WithContext(ctx).Errorf("[logistics db] call GetRecruitStrategyByProjectId error,err:%+v", err)
		return nil, err
	}
	return RecruitStrategys, nil
}
