package usecase

import (
	"context"
	"errors"

	"github.com/gofrs/uuid/v5"

	"github.com/saveinmed/backend-go/internal/domain"
)

// CreateReview stores a buyer rating, ensuring the order is delivered and owned by the requester.
func (s *Service) CreateReview(ctx context.Context, buyerID, orderID uuid.UUID, rating int, comment string) (*domain.Review, error) {
	if rating < 1 || rating > 5 {
		return nil, errors.New("rating must be between 1 and 5")
	}

	order, err := s.repo.GetOrder(ctx, orderID)
	if err != nil {
		return nil, err
	}

	if order.Status != domain.OrderStatusDelivered {
		return nil, errors.New("only delivered orders can be reviewed")
	}

	if order.BuyerID != buyerID {
		return nil, errors.New("order does not belong to buyer")
	}

	review := &domain.Review{
		ID:       uuid.Must(uuid.NewV7()),
		OrderID:  orderID,
		BuyerID:  buyerID,
		SellerID: order.SellerID,
		Rating:   rating,
		Comment:  comment,
	}

	if err := s.repo.CreateReview(ctx, review); err != nil {
		return nil, err
	}
	return review, nil
}

// GetCompanyRating returns the aggregated rating for a seller or pharmacy.
func (s *Service) GetCompanyRating(ctx context.Context, companyID uuid.UUID) (*domain.CompanyRating, error) {
	return s.repo.GetCompanyRating(ctx, companyID)
}

// ListReviews returns a paginated list of reviews matching the filter.
func (s *Service) ListReviews(ctx context.Context, filter domain.ReviewFilter, page, pageSize int) (*domain.ReviewPage, error) {
	if pageSize <= 0 {
		pageSize = 20
	}
	if page <= 0 {
		page = 1
	}
	filter.Limit = pageSize
	filter.Offset = (page - 1) * pageSize
	reviews, total, err := s.repo.ListReviews(ctx, filter)
	if err != nil {
		return nil, err
	}
	return &domain.ReviewPage{Reviews: reviews, Total: total, Page: page, PageSize: pageSize}, nil
}
