package site

import (
	"fmt"

	"go.uber.org/zap"

	"codeberg.org/mapleopentech/monorepo/cloud/maplepress-backend/pkg/security/apikey"
)

// GenerateAPIKeyUseCase generates and hashes an API key
type GenerateAPIKeyUseCase struct {
	apiKeyGen    apikey.Generator
	apiKeyHasher apikey.Hasher
	logger       *zap.Logger
}

// ProvideGenerateAPIKeyUseCase creates a new GenerateAPIKeyUseCase
func ProvideGenerateAPIKeyUseCase(
	apiKeyGen apikey.Generator,
	apiKeyHasher apikey.Hasher,
	logger *zap.Logger,
) *GenerateAPIKeyUseCase {
	return &GenerateAPIKeyUseCase{
		apiKeyGen:    apiKeyGen,
		apiKeyHasher: apiKeyHasher,
		logger:       logger,
	}
}

// APIKeyResult contains the generated API key details
type APIKeyResult struct {
	PlaintextKey string
	HashedKey    string
	Prefix       string
	LastFour     string
}

// Execute generates an API key (test or live) and returns its details
func (uc *GenerateAPIKeyUseCase) Execute(testMode bool) (*APIKeyResult, error) {
	// Generate API key (test or live based on test_mode)
	var apiKey string
	var err error
	if testMode {
		apiKey, err = uc.apiKeyGen.GenerateTest() // test_sk_...
		uc.logger.Info("generating test API key for development")
	} else {
		apiKey, err = uc.apiKeyGen.Generate() // live_sk_...
	}
	if err != nil {
		uc.logger.Error("failed to generate API key", zap.Error(err))
		return nil, fmt.Errorf("failed to generate API key: %w", err)
	}

	// Hash API key
	apiKeyHash := uc.apiKeyHasher.Hash(apiKey)
	apiKeyPrefix := apikey.ExtractPrefix(apiKey)
	apiKeyLastFour := apikey.ExtractLastFour(apiKey)

	uc.logger.Info("API key generated",
		zap.String("prefix", apiKeyPrefix),
		zap.String("last_four", apiKeyLastFour))

	return &APIKeyResult{
		PlaintextKey: apiKey,
		HashedKey:    apiKeyHash,
		Prefix:       apiKeyPrefix,
		LastFour:     apiKeyLastFour,
	}, nil
}
