package service

import (
	"context"
	"git.gocasts.ir/ebhomengo/niki/types"
	"time"
)

func (s *CampaignService) MonitorCampaignProgress(ctx context.Context, req FilterRequest) {

	ticker := time.NewTicker(1 * time.Hour)
	defer ticker.Stop()

	for {
		select {
		case <-ticker.C:
			s.CheckAndCompleteCampaigns(ctx, req)
		case <-ctx.Done():
			return
		}
	}
}

func (s *CampaignService) CheckAndCompleteCampaigns(ctx context.Context, req FilterRequest) (CompletedCampaignResponse, error) {

	now := time.Now()

	//TODO:with filter request later complete
	activeCampaigns, err := s.repoStatus.FindActiveCampaigns(ctx)
	if err != nil {
		return CompletedCampaignResponse{}, err
	}

	var totalChecked uint64
	var totalFinished uint64

	for _, campaign := range activeCampaigns {

		totalChecked++

		shouldFinish := false

		if campaign.DeadlineAt != nil && campaign.DeadlineAt.Before(now) {
			shouldFinish = true
		}

		if campaign.RaisedAmount >= campaign.GoalAmount {
			shouldFinish = true
		}

		if shouldFinish && campaign.Status != types.CampaignFinished {
			if err := s.repoStatus.UpdateStatus(ctx, campaign.ID, types.CampaignFinished); err != nil {
				continue
			}

			totalFinished++
		}
	}

	return CompletedCampaignResponse{
		TotalChecked:  totalChecked,
		TotalFinished: totalFinished,
	}, nil
}
