package site

import (
	"context"

	"github.com/gocql/gocql"
	"go.uber.org/zap"

	siteusecase "codeberg.org/mapleopentech/monorepo/cloud/maplepress-backend/internal/usecase/site"
)

// DeleteSiteService handles site deletion operations
type DeleteSiteService interface {
	DeleteSite(ctx context.Context, tenantID gocql.UUID, input *siteusecase.DeleteSiteInput) (*siteusecase.DeleteSiteOutput, error)
}

type deleteSiteService struct {
	// Focused usecases
	validateSiteForDeletionUC *siteusecase.ValidateSiteForDeletionUseCase
	deleteSiteFromRepoUC      *siteusecase.DeleteSiteFromRepoUseCase

	logger *zap.Logger
}

// NewDeleteSiteService creates a new DeleteSiteService
func NewDeleteSiteService(
	validateSiteForDeletionUC *siteusecase.ValidateSiteForDeletionUseCase,
	deleteSiteFromRepoUC *siteusecase.DeleteSiteFromRepoUseCase,
	logger *zap.Logger,
) DeleteSiteService {
	return &deleteSiteService{
		validateSiteForDeletionUC: validateSiteForDeletionUC,
		deleteSiteFromRepoUC:      deleteSiteFromRepoUC,
		logger:                    logger.Named("delete-site-service"),
	}
}

// DeleteSite orchestrates the site deletion workflow
func (s *deleteSiteService) DeleteSite(ctx context.Context, tenantID gocql.UUID, input *siteusecase.DeleteSiteInput) (*siteusecase.DeleteSiteOutput, error) {
	s.logger.Info("deleting site",
		zap.String("tenant_id", tenantID.String()),
		zap.String("site_id", input.SiteID))

	// Step 1: Parse site ID
	siteID, err := gocql.ParseUUID(input.SiteID)
	if err != nil {
		s.logger.Error("invalid site ID", zap.Error(err))
		return nil, err
	}

	// Step 2: Validate site exists before deletion
	site, err := s.validateSiteForDeletionUC.Execute(ctx, tenantID, siteID)
	if err != nil {
		s.logger.Error("site validation failed",
			zap.String("site_id", input.SiteID),
			zap.Error(err))
		return nil, err
	}

	// Step 3: Delete site from repository (all tables)
	if err := s.deleteSiteFromRepoUC.Execute(ctx, tenantID, siteID); err != nil {
		s.logger.Error("failed to delete site from repository",
			zap.String("site_id", input.SiteID),
			zap.Error(err))
		return nil, err
	}

	s.logger.Info("site deleted successfully",
		zap.String("site_id", input.SiteID),
		zap.String("domain", site.Domain))

	// Step 4: Build output
	return &siteusecase.DeleteSiteOutput{
		Success: true,
		Message: "Site deleted successfully",
	}, nil
}
