package camel_oil

import (
	"context"
	"github.com/gogf/gf/v2/os/gmlock"
	"github.com/gogf/gf/v2/os/gtime"

	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"

	"kami/internal/consts"
	"kami/internal/dao"
	"kami/internal/model/entity"
	"kami/utility/config"
)

// ====================================================================================
// 账号轮询相关方法
// ====================================================================================

// GetAvailableAccount 获取可用账号（按last_used_at轮询）
// 选择条件：
// 1. status=2（在线）
// 2. daily_order_count < 10（当日未达限额）
// 3. daily_order_date=今日（日期匹配）
// 排序：last_used_at ASC（最早使用的优先，实现轮询）
func (s *sCamelOil) GetAvailableAccount(ctx context.Context) (account *entity.V1CamelOilAccount, err error) {
	gmlock.Lock("camelGetAvailableAccount")
	defer gmlock.Unlock("camelGetAvailableAccount")

	m := dao.V1CamelOilAccount.Ctx(ctx).DB(config.GetDatabaseV1())

	err = m.Where(dao.V1CamelOilAccount.Columns().Status, consts.CamelOilAccountStatusOnline).
		WhereLTE(dao.V1CamelOilAccount.Columns().DailyOrderCount, 10).
		OrderAsc(dao.V1CamelOilAccount.Columns().LastUsedAt).
		Scan(&account)

	if err != nil {
		return nil, gerror.Wrap(err, "查询可用账号失败")
	}

	if account == nil {
		g.Log().Warning(ctx, "暂无可用账号")
		return nil, nil
	}
	_, _ = m.Where(dao.V1CamelOilAccount.Columns().Id, account.Id).Update(dao.V1CamelOilAccount.Columns().LastUsedAt, gtime.Now())
	return account, nil
}
