package service

import (
	"time"

	"metazone.cc/metalab/internal/common"
	"metazone.cc/metalab/internal/model"
)

// GetEnergyInfo 获取用户域能余额和每日赋能经验状态
func (s *EnergyService) GetEnergyInfo(userID uint) (*EnergyInfo, error) {
	user, err := s.repo.FindUserByID(userID)
	if err != nil {
		return nil, err
	}

	loc, _ := time.LoadLocation("Asia/Shanghai")
	now := time.Now().In(loc)
	today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, loc)

	dailyExp := 0
	summary, err := s.repo.GetDailyEnergizeExp(userID, today)
	if err == nil && summary != nil {
		dailyExp = summary.ExpEarned
	}

	return &EnergyInfo{
		Energy:             user.Energy,
		DailyEnergizeExp:   dailyExp,
		DailyExpCap:        DailyEnergizeExpCap,
		DailyExpCapReached: dailyExp >= DailyEnergizeExpCap,
	}, nil
}

// GetEnergyLogs 分页查询用户域能流水（近 N 天）
func (s *EnergyService) GetEnergyLogs(userID uint, days, page, pageSize int) ([]model.EnergyLog, int64, error) {
	p := common.Pagination{Page: page, PageSize: pageSize}
	p.DefaultPagination()

	total, err := s.repo.CountEnergyLogsByUser(userID, days)
	if err != nil {
		return nil, 0, err
	}

	logs, err := s.repo.ListEnergyLogsByUser(userID, days, p.Offset(), p.PageSize)
	if err != nil {
		return nil, 0, err
	}
	if logs == nil {
		logs = []model.EnergyLog{}
	}
	return logs, total, nil
}

// GetAdminEnergyLogs 后台查询全部域能流水
func (s *EnergyService) GetAdminEnergyLogs(energyType string, page, pageSize int) ([]model.EnergyLog, int64, error) {
	p := common.Pagination{Page: page, PageSize: pageSize}
	p.DefaultPagination()
	return s.repo.ListAllEnergyLogs(energyType, p.Offset(), p.PageSize)
}

// GetFundBalance 获取公户余额
func (s *EnergyService) GetFundBalance() (int, error) {
	if s.fundRepo == nil {
		return 0, nil
	}
	return s.fundRepo.GetBalance()
}

// GetFundLogs 分页查询公户流水
func (s *EnergyService) GetFundLogs(logType string, page, pageSize int) ([]model.FundLog, int64, error) {
	p := common.Pagination{Page: page, PageSize: pageSize}
	p.DefaultPagination()
	if s.fundRepo == nil {
		return []model.FundLog{}, 0, nil
	}
	logs, total, err := s.fundRepo.ListLogs(logType, p.Offset(), p.PageSize)
	if err != nil {
		return nil, 0, err
	}
	if logs == nil {
		logs = []model.FundLog{}
	}
	return logs, total, nil
}
