package service

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

	"kra/internal/service/dto"
)

type TokenService struct {
	uc     *system.TokenUsecase
	issuer system.TokenIssuer
}

func NewTokenService(uc *system.TokenUsecase, issuer system.TokenIssuer) *TokenService {
	return &TokenService{uc: uc, issuer: issuer}
}

func tokenDTO(v *system.APIToken) *dto.APITokenResponse {
	var user *dto.UserResponse
	if v.User != nil {
		user = convertUser(v.User)
	}
	return &dto.APITokenResponse{ID: v.ID, CreatedAt: v.CreatedAt, UpdatedAt: v.UpdatedAt, DeletedAt: nil, UserID: v.UserID, AuthorityID: v.AuthorityID, Token: v.Token, Status: v.Status, ExpiresAt: v.ExpiresAt, Remark: v.Remark, User: user}
}

func (s *TokenService) CreateAPIToken(ctx context.Context, userID, authorityID uint, days int, remark string) (string, error) {
	user, duration, err := s.uc.PrepareAPIToken(ctx, userID, authorityID, days)
	if err != nil {
		return "", err
	}
	issued, err := s.issuer.IssueToken(user, authorityID, false, duration)
	if err != nil {
		return "", err
	}
	record := &system.APIToken{UserID: userID, AuthorityID: authorityID, Token: issued.Value, Status: true, ExpiresAt: time.Now().Add(duration), Remark: remark}
	if err = s.uc.CreateAPIToken(ctx, record); err != nil {
		return "", err
	}
	return issued.Value, nil
}
func (s *TokenService) APITokens(ctx context.Context, page, size int, userID uint, status *bool) ([]*dto.APITokenResponse, int64, error) {
	items, total, err := s.uc.ListAPITokens(ctx, page, size, userID, status)
	if err != nil {
		return nil, 0, err
	}
	out := make([]*dto.APITokenResponse, 0, len(items))
	for _, v := range items {
		out = append(out, tokenDTO(v))
	}
	return out, total, nil
}
func (s *TokenService) DisableAPIToken(ctx context.Context, id uint) error {
	return s.uc.DisableToken(ctx, id)
}
func (s *TokenService) BlacklistToken(ctx context.Context, token string) error {
	return s.uc.BlacklistToken(ctx, token)
}
func (s *TokenService) IsTokenDisabled(ctx context.Context, token string) (bool, error) {
	return s.uc.IsTokenDisabled(ctx, token)
}
