package dao

import (
	"errors"
	"gorm.io/gorm"
	"youngee_b_api/app/entity"
)

type TeamBuyingDao struct{}

func (d TeamBuyingDao) CreateTeamBuying(teamBuying entity.TeamBuying) (int64, error) {
	err := Db.Model(&entity.TeamBuying{}).Create(&teamBuying).Error
	if err != nil {
		return 0, err
	}
	return teamBuying.TeamBuyingID, nil
}

func (d TeamBuyingDao) UpdateTeamBuying(teamBuying entity.TeamBuying) (int64, error) {
	err := Db.Model(&entity.TeamBuying{}).Where("team_buying_id = ?", teamBuying.TeamBuyingID).Updates(teamBuying).Error
	if err != nil {
		return 0, err
	}
	return teamBuying.TeamBuyingID, nil
}

func (d TeamBuyingDao) DeleteTeamBuying(teamBuyingId int64) error {
	err := Db.Where("team_buying_id = ?", teamBuyingId).Delete(&entity.TeamBuying{}).Error
	return err
}

func (d TeamBuyingDao) GetTeamBuyingByID(teamBuyingId int64) (*entity.TeamBuying, error) {
	var teamBuying entity.TeamBuying
	err := Db.Debug().Where("team_buying_id = ?", teamBuyingId).First(&teamBuying).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		} else {
			return nil, err
		}
	}
	return &teamBuying, nil
}

func (d TeamBuyingDao) GetTeamBuyingsByStoreId(storeId int64, page int, pageSize int) ([]entity.TeamBuying, int64, error) {
	var teamBuyings []entity.TeamBuying
	var total int64
	query := Db.Model(&entity.TeamBuying{}).Where("store_id = ? AND is_deleted = ?", storeId, 0)
	query.Count(&total)
	// 计算偏移量
	offset := (page - 1) * pageSize
	// 分页查询
	err := Db.Model(&entity.TeamBuying{}).Where("store_id = ? AND is_deleted = ?", storeId, 0).Order("created_at desc").Offset(offset).Limit(pageSize).Find(&teamBuyings).Error
	if err != nil {
		return nil, 0, err
	}
	return teamBuyings, total, nil
}

func (d TeamBuyingDao) GetTeamBuyingsByStoreIdAndTeamBuyingTitle(storeId int64, teamBuyingTitle string, page int, pageSize int) ([]entity.TeamBuying, int64, error) {
	var teamBuyings []entity.TeamBuying
	var total int64
	query := Db.Model(&entity.TeamBuying{}).Where("store_id = ? AND is_deleted = ?", storeId, 0)
	if teamBuyingTitle != "" {
		query = query.Where("team_buying_name LIKE ?", "%"+teamBuyingTitle+"%")
	}
	query.Count(&total)
	// 计算偏移量
	offset := (page - 1) * pageSize
	// 分页查询
	err := Db.Model(&entity.TeamBuying{}).Where("store_id = ? AND is_deleted = ?", storeId, 0).Order("created_at desc").Offset(offset).Limit(pageSize).Find(&teamBuyings).Error
	if err != nil {
		return nil, 0, err
	}
	return teamBuyings, total, nil
}
