package usecase

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

	"github.com/google/uuid"
)

type packageUsecase struct {
	repo domain.PackageRepository
}

func NewPackageUsecase(repo domain.PackageRepository) domain.PackageUsecase {
	return &packageUsecase{repo: repo}
}

func (u *packageUsecase) CreatePackage(ctx context.Context, pkg *domain.Package) error {
	pkg.ID = uuid.New()
	pkg.CreatedAt = time.Now()
	pkg.UpdatedAt = time.Now()
	return u.repo.Create(ctx, pkg)
}

func (u *packageUsecase) GetPackageByID(ctx context.Context, id uuid.UUID) (*domain.Package, error) {
	pkg, err := u.repo.GetByID(ctx, id)
	if err != nil {
		return nil, errors.New("package not found")
	}
	return pkg, nil
}

func (u *packageUsecase) GetAllPackages(ctx context.Context) ([]domain.Package, error) {
	return u.repo.List(ctx)
}

func (u *packageUsecase) UpdatePackage(ctx context.Context, id uuid.UUID, pkg *domain.Package) error {
	existing, err := u.repo.GetByID(ctx, id)
	if err != nil {
		return errors.New("package not found")
	}
	existing.Name = pkg.Name
	existing.Description = pkg.Description
	existing.Price = pkg.Price
	existing.BillingCycle = pkg.BillingCycle
	existing.OrderNumber = pkg.OrderNumber
	existing.MaxCandidatesPerMonth = pkg.MaxCandidatesPerMonth
	existing.MaxUsers = pkg.MaxUsers
	existing.HighlightPackage = pkg.HighlightPackage
	existing.BadgeLabel = pkg.BadgeLabel
	existing.ButtonText = pkg.ButtonText
	existing.ButtonVariant = pkg.ButtonVariant
	existing.IsFeatureAllTests = pkg.IsFeatureAllTests
	existing.IsFeaturePdfReport = pkg.IsFeaturePdfReport
	existing.IsFeatureDashboard = pkg.IsFeatureDashboard
	existing.IsFeaturePrioritySupport = pkg.IsFeaturePrioritySupport
	existing.IsFeatureApiAccess = pkg.IsFeatureApiAccess
	existing.IsFeatureCustomBranding = pkg.IsFeatureCustomBranding
	existing.IsFeatureMultiUser = pkg.IsFeatureMultiUser
	existing.IsFeatureExportExcel = pkg.IsFeatureExportExcel
	existing.IsFeatureCandidateHistory = pkg.IsFeatureCandidateHistory
	existing.IsFeatureAiInsight = pkg.IsFeatureAiInsight
	existing.ThemeColor = pkg.ThemeColor
	return u.repo.Update(ctx, existing)
}

func (u *packageUsecase) DeletePackage(ctx context.Context, id uuid.UUID) error {
	_, err := u.repo.GetByID(ctx, id)
	if err != nil {
		return errors.New("package not found")
	}
	return u.repo.Delete(ctx, id)
}
