package service

import (
	"context"
	"fmt"
	"github.com/go-nunu/nunu-layout-advanced/internal/repository"
	"strconv"
	"time"
)

type DuedateService interface {
	NextDueDate(ctx context.Context, uid int, hostId int) (string, error)
}

func NewDuedateService(
	service *Service,
	gameShieldRepository repository.GameShieldRepository,

) DuedateService {
	return &duedateService{
		Service:              service,
		gameShieldRepository: gameShieldRepository,
	}
}

type duedateService struct {
	*Service
	gameShieldRepository repository.GameShieldRepository
}

func (service *duedateService) NextDueDate(ctx context.Context, uid int, productID int) (string, error) {
	timeStr, err := service.gameShieldRepository.GetGameShieldNextduedate(ctx, int64(uid), productID)
	if err != nil {
		return "", err
	}
	if timeStr == "0" || timeStr == "" {
		return "", fmt.Errorf("产品不存在")
	}

	// 将字符串转为 int64 时间戳
	unixTime, err := strconv.ParseInt(timeStr, 10, 64)
	if err != nil {
		return "", err
	}
	now := time.Now().Unix() // 当前时间戳（秒级）
	if now > unixTime {
		return "", fmt.Errorf("产品已过期,请及时续费")
	}
	// 格式化时间
	t := time.Unix(unixTime, 0)
	nextduedate := t.Add(time.Hour).Format("2006-01-02 15:04:05")

	return nextduedate, nil
}
