package privilegewc

import (
	"context"
	"fmt"
	"penahub.gitlab.yandexcloud.net/backend/quiz/common.git/dal"
	"penahub.gitlab.yandexcloud.net/backend/quiz/common.git/model"
	"penahub.gitlab.yandexcloud.net/pena-services/customer/pkg/customer_clients"
	"time"
)

type Deps struct {
	PrivilegeDAL      *dal.DAL
	TickerInterval    time.Duration
	PrivilegeIDsDays  []string
	PrivilegeIDsCount []string
	CustomerClient    *customer_clients.CustomersClient
}

type CheckWorker struct {
	privilegeDAL      *dal.DAL
	tickerInterval    time.Duration
	errChan           chan<- error
	privilegeIDsDays  []string
	privilegeIDsCount []string
	customerClient    *customer_clients.CustomersClient
}

func NewCheckWorker(deps Deps, errChan chan<- error) *CheckWorker {
	return &CheckWorker{
		privilegeDAL:      deps.PrivilegeDAL,
		tickerInterval:    deps.TickerInterval,
		errChan:           errChan,
		privilegeIDsCount: deps.PrivilegeIDsCount,
		privilegeIDsDays:  deps.PrivilegeIDsDays,
		customerClient:    deps.CustomerClient,
	}
}

func (w *CheckWorker) Start(ctx context.Context) {
	ticker := time.NewTicker(w.tickerInterval)
	defer ticker.Stop()

	for {
		select {
		case <-ticker.C:
			fmt.Println("CHECK")
			w.deleteExpired(ctx)
		case <-ctx.Done():
			fmt.Println("Check worker terminated")
			return
		}
	}
}

func (w *CheckWorker) deleteExpired(ctx context.Context) {
	var toHistory []customer_clients.InsertHistoryDeps
	var expiredData []model.ExpiredPrivileges

	for _, id := range w.privilegeIDsDays {
		expired, err := w.privilegeDAL.AccountRepo.GetExpired(ctx, id)
		if err != nil {
			w.errChan <- err
		}
		expiredData = append(expiredData, expired...)
	}

	for _, id := range w.privilegeIDsCount {
		expired, err := w.privilegeDAL.AccountRepo.GetExpiredCount(ctx, id)
		if err != nil {
			w.errChan <- err
		}
		expiredData = append(expiredData, expired...)
	}

	for _, data := range expiredData {
		err := w.privilegeDAL.AccountRepo.DeletePrivilegeByID(ctx, data.Privilege.ID)
		if err != nil {
			w.errChan <- err
			continue
		}

		toHistory = append(toHistory, customer_clients.InsertHistoryDeps{
			UserID:  data.UserID,
			Comment: fmt.Sprintf("%s privilege has expired, it was created at %d", data.Privilege.PrivilegeID, data.Privilege.CreatedAt.Unix()),
			Key:     "privilege_expired",
		})
	}

	for _, to := range toHistory {
		err := w.customerClient.InsertHistory(ctx, to)
		if err != nil {
			w.errChan <- err
		}
	}
}
