package site

import (
	"context"
	"fmt"

	"go.uber.org/zap"

	domainsite "codeberg.org/mapleopentech/monorepo/cloud/maplepress-backend/internal/domain/site"
)

// UpdateSiteAPIKeyToRepoInput defines the input for updating a site's API key in the repository
type UpdateSiteAPIKeyToRepoInput struct {
	Site          *domainsite.Site
	OldAPIKeyHash string
}

// UpdateSiteAPIKeyToRepoUseCase updates a site's API key in the repository (all tables)
// This use case properly handles the sites_by_apikey table by deleting the old entry
// and inserting a new one, since api_key_hash is part of the primary key
type UpdateSiteAPIKeyToRepoUseCase struct {
	repo   domainsite.Repository
	logger *zap.Logger
}

// NewUpdateSiteAPIKeyToRepoUseCase creates a new UpdateSiteAPIKeyToRepoUseCase
func NewUpdateSiteAPIKeyToRepoUseCase(
	repo domainsite.Repository,
	logger *zap.Logger,
) *UpdateSiteAPIKeyToRepoUseCase {
	return &UpdateSiteAPIKeyToRepoUseCase{
		repo:   repo,
		logger: logger.Named("update-site-apikey-to-repo-usecase"),
	}
}

// ProvideUpdateSiteAPIKeyToRepoUseCase creates a new UpdateSiteAPIKeyToRepoUseCase for dependency injection
func ProvideUpdateSiteAPIKeyToRepoUseCase(
	repo domainsite.Repository,
	logger *zap.Logger,
) *UpdateSiteAPIKeyToRepoUseCase {
	return NewUpdateSiteAPIKeyToRepoUseCase(repo, logger)
}

// Execute updates a site's API key in the repository (all tables)
func (uc *UpdateSiteAPIKeyToRepoUseCase) Execute(ctx context.Context, input *UpdateSiteAPIKeyToRepoInput) error {
	if err := uc.repo.UpdateAPIKey(ctx, input.Site, input.OldAPIKeyHash); err != nil {
		uc.logger.Error("failed to update site API key in repository",
			zap.String("site_id", input.Site.ID.String()),
			zap.String("old_key_hash", input.OldAPIKeyHash),
			zap.Error(err))
		return fmt.Errorf("failed to update site API key: %w", err)
	}

	uc.logger.Info("site API key updated in repository",
		zap.String("site_id", input.Site.ID.String()),
		zap.String("domain", input.Site.Domain),
		zap.String("new_key_prefix", input.Site.APIKeyPrefix),
		zap.String("new_key_last_four", input.Site.APIKeyLastFour))

	return nil
}
