package packs

import (
	"context"
	"database/sql"
	"time"

	"github.com/rs/zerolog/log"
)

// ensureFolderOrganizationShares creates Organization-level View shares for
// existing public folders that are missing their Organization baseline share.
func ensureFolderOrganizationShares(ctx context.Context, db *sql.DB) error {
	log.Info().Msg("🔧 Ensuring folder organization shares...")
	start := time.Now()

	result, err := db.ExecContext(ctx, `
		INSERT INTO FolderShare (Id, FolderId, SharedToId, SharedToType, AccessLevel, CreatedById, CreatedDate, LastModifiedDate)
		SELECT
			CONCAT('FS_ORG_', rf.Id),
			rf.Id,
			'ALL_INTERNAL',
			'Organization',
			'View',
			'SYSTEM',
			NOW(),
			NOW()
		FROM ReportFolder rf
		WHERE rf.AccessType = 'Public'
			AND (rf.IsDeleted = 0 OR rf.IsDeleted IS NULL)
			AND NOT EXISTS (
				SELECT 1 FROM FolderShare fs WHERE fs.FolderId = rf.Id AND fs.SharedToType = 'Organization'
			)
	`)
	if err != nil {
		log.Warn().Err(err).Msg("Failed to ensure folder organization shares")
		return err
	}

	rows, _ := result.RowsAffected()
	log.Info().
		Int64("sharesCreated", rows).
		Dur("elapsed", time.Since(start)).
		Msg("✅ Folder organization shares ensured")

	return nil
}
