package adminauth

import (
	"errors"

	"hfb_sys/backend/internal/modules/auth"
)

var (
	ErrDependencyUnavailable = errors.New("dependency unavailable")
	ErrInvalidCredential     = errors.New("invalid credential")
	ErrCaptchaInvalid        = errors.New("captcha invalid")
	ErrAdminDisabled         = errors.New("admin disabled")
	ErrInvalidRefreshToken   = errors.New("invalid refresh token")
)

type Service struct {
	repo *Repository
	jwt  *auth.JWTManager
}

func NewService(repo *Repository, jwt *auth.JWTManager) *Service {
	return &Service{repo: repo, jwt: jwt}
}

func (s *Service) Refresh(refreshToken string) (*auth.TokenPair, error) {
	if s.jwt == nil {
		return nil, ErrDependencyUnavailable
	}
	claims, err := s.jwt.ParseSubject(refreshToken, "refresh", "admin")
	if err != nil {
		return nil, ErrInvalidRefreshToken
	}
	pair, err := s.jwt.GenerateSubjectPair(claims.UserID, claims.Phone, "admin")
	if err != nil {
		return nil, err
	}
	return &pair, nil
}

func (s *Service) Captcha() (*CaptchaDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	return s.repo.Captcha()
}

func (s *Service) Login(username string, password string, captchaID string, captchaCode string) (LoginResult, error) {
	if s.repo == nil {
		return LoginResult{}, ErrDependencyUnavailable
	}
	if username == "" || password == "" || captchaID == "" || captchaCode == "" {
		return LoginResult{}, ErrInvalidCredential
	}
	return s.repo.Login(username, password, captchaID, captchaCode)
}

func (s *Service) Me(adminID uint64) (*AdminDTO, error) {
	if s.repo == nil {
		return nil, ErrDependencyUnavailable
	}
	return s.repo.FindByID(adminID)
}

func (s *Service) UpdateSupportStatus(adminID uint64, status string) error {
	if s.repo == nil {
		return ErrDependencyUnavailable
	}
	return s.repo.UpdateSupportStatus(adminID, status)
}
