package usecase

import (
	"context"
	"lune/talentscale/internal/domain"
	"time"

	"github.com/google/uuid"
)

type subscriptionUsecase struct {
	subRepo domain.SubscriptionRepository
	pkgRepo domain.PackageRepository
}

func NewSubscriptionUsecase(subRepo domain.SubscriptionRepository, pkgRepo domain.PackageRepository) domain.SubscriptionUsecase {
	return &subscriptionUsecase{subRepo: subRepo, pkgRepo: pkgRepo}
}

func (u *subscriptionUsecase) Subscribe(ctx context.Context, companyID, packageID uuid.UUID) (*domain.Subscription, error) {
	// Validate the package exists
	pkg, err := u.pkgRepo.GetByID(ctx, packageID)
	if err != nil {
		return nil, err
	}

	now := time.Now()
	var endDate time.Time
	if pkg.BillingCycle == "YEARLY" {
		endDate = now.AddDate(1, 0, 0)
	} else {
		endDate = now.AddDate(0, 1, 0)
	}

	sub := &domain.Subscription{
		ID:        uuid.New(),
		CompanyID: companyID,
		PackageID: packageID,
		StartDate: now,
		EndDate:   endDate,
		Status:    "ACTIVE",
		CreatedAt: now,
		UpdatedAt: now,
	}

	if err := u.subRepo.Create(ctx, sub); err != nil {
		return nil, err
	}
	return sub, nil
}

func (u *subscriptionUsecase) GetActiveSubscription(ctx context.Context, companyID uuid.UUID) (*domain.Subscription, error) {
	return u.subRepo.GetActiveByCompanyID(ctx, companyID)
}
