package packs

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

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

// ensureFolderOrganizationShares creates Organization-level View shares only
// for platform-config's declared default folders. It must not scan every
// public folder: init-l0 has to be an L0-only write path even when reused DBs
// contain app-pack residue.
func ensureFolderOrganizationShares(ctx context.Context, db *sql.DB) error {
	log.Info().Msg("🔧 Ensuring folder organization shares...")
	start := time.Now()

	var totalCreated int64
	for _, folder := range defaultReportFolders() {
		result, err := db.ExecContext(ctx, `
			INSERT INTO FolderShare (Id, FolderId, SharedToId, SharedToType, AccessLevel, CreatedById, CreatedDate, LastModifiedDate)
			SELECT
				?,
				rf.Id,
				'ALL_INTERNAL',
				'Organization',
				'View',
				'SYSTEM',
				NOW(),
				NOW()
			FROM ReportFolder rf
			WHERE rf.Id = ?
				AND rf.AccessType = 'Public'
				AND (rf.IsDeleted = 0 OR rf.IsDeleted IS NULL)
				AND NOT EXISTS (
					SELECT 1 FROM FolderShare fs WHERE fs.Id = ?
				)
		`, folderOrganizationShareID(folder.ID), folder.ID, folderOrganizationShareID(folder.ID))
		if err != nil {
			log.Warn().Err(err).Str("folder_id", folder.ID).Msg("Failed to ensure folder organization share")
			return err
		}
		rows, _ := result.RowsAffected()
		totalCreated += rows
	}

	log.Info().
		Int64("sharesCreated", totalCreated).
		Dur("elapsed", time.Since(start)).
		Msg("✅ Folder organization shares ensured")

	return nil
}
