package pickup

import (
	"context"

	"hfb_sys/backend/internal/auditlog"
)

type Service struct {
	repo *Repository
}

func NewService(repo *Repository) *Service {
	return &Service{repo: repo}
}

func (s *Service) Create(ctx context.Context, req CreateRequest, adminID uint64, meta auditlog.Meta) (*PickupDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	if req.ListingID == 0 {
		return nil, ErrListingUnavailable
	}
	if req.ProfitAmountCent < 0 {
		return nil, ErrInvalidProfit
	}
	return s.repo.Create(ctx, req, adminID, meta)
}

func (s *Service) Complete(ctx context.Context, pickupID uint64, req CompleteRequest, adminID uint64, meta auditlog.Meta) (*PickupDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	if pickupID == 0 || req.SettleAmountCent <= 0 {
		return nil, ErrInvalidAmount
	}
	if req.ProfitAmountCent != nil && *req.ProfitAmountCent < 0 {
		return nil, ErrInvalidProfit
	}
	return s.repo.Complete(ctx, pickupID, req, adminID, meta)
}

func (s *Service) Cancel(ctx context.Context, pickupID uint64, reason string, adminID uint64, meta auditlog.Meta) error {
	if s.repo == nil {
		return ErrDependencyUnavailable
	}
	if pickupID == 0 || reason == "" {
		return ErrPickupNotPickingUp
	}
	return s.repo.Cancel(ctx, pickupID, reason, adminID, meta)
}

func (s *Service) FindByID(ctx context.Context, id uint64) (*PickupDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	return s.repo.FindByID(ctx, id)
}

func (s *Service) ListAdmin(ctx context.Context, query AdminPickupQuery) (*PaginatedResult, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	return s.repo.ListAdmin(ctx, query)
}

func (s *Service) ListForSeller(ctx context.Context, ownerID uint64, query SellerPickupQuery) (*PaginatedResult, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	return s.repo.ListForSeller(ctx, ownerID, query)
}

func (s *Service) ListAvailableListings(ctx context.Context, keyword string, page, pageSize int) (*AvailableListingsResult, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	return s.repo.ListAvailableListings(ctx, keyword, page, pageSize)
}
