package service

import (
	"context"
	"kra/internal/biz/system"

	"kra/internal/service/dto"
)

type AuthService struct {
	uc *system.AuthenticationUsecase
}

func NewAuthService(uc *system.AuthenticationUsecase) *AuthService {
	return &AuthService{uc: uc}
}

func loginResult(value *system.AuthenticationResult) *dto.LoginResponse {
	return &dto.LoginResponse{User: convertUser(value.User), Token: value.Token, ExpiresAt: value.ExpiresAt.UnixMilli(), NeedChangePassword: value.NeedChangePassword}
}

func (s *AuthService) Login(ctx context.Context, req *dto.LoginRequest, ip, agent string) (*dto.LoginResponse, error) {
	value, err := s.uc.Login(ctx, &system.LoginAttempt{Username: req.Username, Password: req.Password, CaptchaID: req.CaptchaID, Captcha: req.Captcha, IP: ip, Agent: agent})
	if err != nil {
		return nil, err
	}
	return loginResult(value), nil
}

func (s *AuthService) SwitchAuthority(ctx context.Context, claims *system.AuthClaims, authorityID uint) (*dto.LoginResponse, error) {
	value, err := s.uc.SwitchAuthority(ctx, claims, authorityID)
	if err != nil {
		return nil, err
	}
	return loginResult(value), nil
}

func (s *AuthService) AuthenticateToken(ctx context.Context, token string) (*system.TokenAuthentication, error) {
	return s.uc.AuthenticateToken(ctx, token)
}
