package repository

import (
	"cron_admin/app/http/entities"
	"time"
	"xorm.io/xorm"
)

type DBOption func(session *xorm.Session) *xorm.Session

func (c *CommonRepo[P]) WithByID(id uint) DBOption {
	return func(g *xorm.Session) *xorm.Session {
		return g.Where("id = ?", id)
	}
}

func (c *CommonRepo[P]) WithByUserId(userId uint) DBOption {
	return func(g *xorm.Session) *xorm.Session {
		return g.Where("user_id = ?", userId)
	}
}

func (c *CommonRepo[P]) WithByBrandId(id int) DBOption {
	return func(g *xorm.Session) *xorm.Session {
		return g.Where("brand_id = ?", id)
	}
}

func (c *CommonRepo[P]) WithByDate(startTime, endTime time.Time) DBOption {
	return func(g *xorm.Session) *xorm.Session {
		return g.Where("create_time > ? AND create_time < ?", startTime, endTime)
	}
}

func (c *CommonRepo[P]) WithByUpdateDate(startTime, endTime time.Time) DBOption {
	return func(g *xorm.Session) *xorm.Session {
		return g.Where("update_time > ? AND update_time < ?", startTime, endTime)
	}
}

func (c *CommonRepo[P]) WithByStartDate(startTime time.Time) DBOption {
	return func(g *xorm.Session) *xorm.Session {
		return g.Where("create_time > ?", startTime)
	}
}

func (c *CommonRepo[P]) WithByEndDate(endTime time.Time) DBOption {
	return func(g *xorm.Session) *xorm.Session {
		return g.Where("create_time < ?", endTime)
	}
}

func (c *CommonRepo[P]) WithByStatus(status int) DBOption {
	return func(g *xorm.Session) *xorm.Session {
		if status == 0 {
			return g
		}
		return g.Where("status = ?", status)
	}
}

func (c *CommonRepo[P]) WithByFrom(from string) DBOption {
	return func(g *xorm.Session) *xorm.Session {
		return g.Where("`from` = ?", from)
	}
}

func (c *CommonRepo[P]) WithLikeName(name string) DBOption {
	return func(g *xorm.Session) *xorm.Session {
		if len(name) == 0 {
			return g
		}
		return g.Where("name like ?", "%"+name+"%")
	}
}

func (c *CommonRepo[P]) WithDesc(orderStr string) DBOption {
	return func(g *xorm.Session) *xorm.Session {
		return g.Desc(orderStr)
	}
}

func (c *CommonRepo[P]) WithIdsIn(ids []uint) DBOption {
	return func(g *xorm.Session) *xorm.Session {
		return g.In("id", ids)
	}
}

func (c *CommonRepo[P]) WithIdsNotIn(ids []uint) DBOption {
	return func(g *xorm.Session) *xorm.Session {
		return g.Where("id not in (?)", ids)
	}
}

func (c *CommonRepo[P]) WithPage(pageFilter entities.PageRequest) DBOption {
	return func(g *xorm.Session) *xorm.Session {
		return g.Limit(pageFilter.Limit, pageFilter.Limit*(pageFilter.Page-1))
	}
}
func (c *CommonRepo[P]) WithByCouponId(couponId uint) DBOption {
	return func(g *xorm.Session) *xorm.Session {
		return g.Where("coupon_id =?", couponId)
	}
}

func (c *CommonRepo[P]) WithByProductId(productId uint) DBOption {
	return func(g *xorm.Session) *xorm.Session {
		return g.Where("product_id =?", productId)
	}
}