package ratings

import (
	"Yimaru-Backend/internal/domain"
	"Yimaru-Backend/internal/ports"
	"context"
	"fmt"
)

type Service struct {
	ratingStore ports.RatingStore
}

func NewService(ratingStore ports.RatingStore) *Service {
	return &Service{
		ratingStore: ratingStore,
	}
}

func (s *Service) SubmitRating(ctx context.Context, userID int64, targetType domain.RatingTargetType, targetID int64, stars int16, review *string) (domain.Rating, error) {
	if stars < 1 || stars > 5 {
		return domain.Rating{}, fmt.Errorf("stars must be between 1 and 5")
	}
	if targetType != domain.RatingTargetApp && targetType != domain.RatingTargetCourse && targetType != domain.RatingTargetSubCourse {
		return domain.Rating{}, fmt.Errorf("invalid target type: %s", targetType)
	}
	return s.ratingStore.UpsertRating(ctx, userID, targetType, targetID, stars, review)
}

func (s *Service) GetMyRating(ctx context.Context, userID int64, targetType domain.RatingTargetType, targetID int64) (domain.Rating, error) {
	return s.ratingStore.GetRatingByUserAndTarget(ctx, userID, targetType, targetID)
}

func (s *Service) GetRatingsByTarget(ctx context.Context, targetType domain.RatingTargetType, targetID int64, limit, offset int32) ([]domain.Rating, error) {
	return s.ratingStore.GetRatingsByTarget(ctx, targetType, targetID, limit, offset)
}

func (s *Service) GetRatingSummary(ctx context.Context, targetType domain.RatingTargetType, targetID int64) (domain.RatingSummary, error) {
	return s.ratingStore.GetRatingSummary(ctx, targetType, targetID)
}

func (s *Service) GetUserRatings(ctx context.Context, userID int64) ([]domain.Rating, error) {
	return s.ratingStore.GetUserRatings(ctx, userID)
}

func (s *Service) DeleteRating(ctx context.Context, ratingID, userID int64) error {
	return s.ratingStore.DeleteRating(ctx, ratingID, userID)
}
