package dispute

import (
	"context"
	"errors"
)

var (
	ErrDependencyUnavailable = errors.New("dependency unavailable")
	ErrPermissionDenied      = errors.New("permission denied")
	ErrInvalidDispute        = errors.New("invalid dispute")
	ErrDisputeExists         = errors.New("dispute already exists")
	ErrDisputeCannotHandle   = errors.New("dispute cannot handle")
	ErrDisputeCannotCancel   = errors.New("dispute cannot cancel")
)

type Service struct {
	repo *Repository
}

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

func (s *Service) Create(ctx context.Context, userID uint64, orderID uint64, req CreateRequest) (*DisputeDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	if orderID == 0 || req.Type == "" || req.Description == "" {
		return nil, ErrInvalidDispute
	}
	return s.repo.Create(ctx, userID, orderID, req)
}

func (s *Service) ListForUser(ctx context.Context, userID uint64, page, pageSize int) (*PaginatedResult, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	return s.repo.ListForUser(ctx, userID, page, pageSize)
}

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

func (s *Service) Cancel(ctx context.Context, userID uint64, id uint64) (*DisputeDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	if id == 0 {
		return nil, ErrInvalidDispute
	}
	return s.repo.Cancel(ctx, userID, id)
}

func (s *Service) CancelByOrder(ctx context.Context, userID uint64, orderID uint64) (*DisputeDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	if orderID == 0 {
		return nil, ErrInvalidDispute
	}
	return s.repo.CancelByOrder(ctx, userID, orderID)
}

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

func (s *Service) Arbitrate(ctx context.Context, adminID uint64, id uint64, req ArbitrateRequest, meta AuditMeta) (*DisputeDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	if id == 0 || req.Result == "" || req.Remark == "" {
		return nil, ErrInvalidDispute
	}
	return s.repo.Arbitrate(ctx, adminID, id, req, meta)
}
