package paymentaccount

import (
	"context"
	"errors"
)

var (
	ErrDependencyUnavailable = errors.New("dependency unavailable")
	ErrAccountNotFound       = errors.New("payment account not found")
	ErrAccountNameMismatch   = errors.New("account name must match realname")
	ErrRealnameRequired      = errors.New("realname verification required")
	ErrAccountLimit          = errors.New("maximum payment accounts reached")
	ErrCannotDeleteDefault   = errors.New("cannot delete default account")
)

type Service struct {
	repo *Repository
}

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

func (s *Service) List(ctx context.Context, userID uint64, page, pageSize int) (*PaginatedResult, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	if page < 1 {
		page = 1
	}
	if pageSize < 1 || pageSize > 100 {
		pageSize = 20
	}
	return s.repo.List(ctx, userID, page, pageSize)
}

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

func (s *Service) Create(ctx context.Context, userID uint64, req CreatePaymentAccountRequest) (*PaymentAccountDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	// 验证实名状态
	if err := s.repo.ValidateRealname(ctx, userID, req.AccountName); err != nil {
		return nil, err
	}
	// 检查账号数量限制（最多5个）
	count, err := s.repo.CountByUser(ctx, userID)
	if err != nil {
		return nil, err
	}
	if count >= 5 {
		return nil, ErrAccountLimit
	}
	return s.repo.Create(ctx, userID, req)
}

func (s *Service) Update(ctx context.Context, userID, id uint64, req UpdatePaymentAccountRequest) (*PaymentAccountDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	return s.repo.Update(ctx, userID, id, req)
}

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

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