package repository

import (
	"context"

	"gorm.io/gorm"
)

func CountOrphanUserTenantMemberships(ctx context.Context, db *gorm.DB) (int64, error) {
	var count int64
	err := db.WithContext(ctx).Raw(`
SELECT COUNT(*)
FROM users AS u
WHERE u.deleted_at IS NULL
  AND (
	u.tenant_id IS NOT NULL
	AND NOT EXISTS (
		SELECT 1
		FROM tenants AS t
		WHERE t.id = u.tenant_id
		  AND t.deleted_at IS NULL
	)
  )
`).Scan(&count).Error
	return count, err
}

func ClearOrphanUserTenantMemberships(ctx context.Context, db *gorm.DB) (int64, error) {
	result := db.WithContext(ctx).Exec(`
WITH orphan_users AS (
	SELECT u.id
	FROM users AS u
	WHERE u.deleted_at IS NULL
	  AND (
		u.tenant_id IS NOT NULL
		AND NOT EXISTS (
			SELECT 1
			FROM tenants AS t
			WHERE t.id = u.tenant_id
			  AND t.deleted_at IS NULL
		)
	  )
)
UPDATE users AS u
SET tenant_id = NULL,
	updated_at = NOW()
FROM orphan_users AS ou
WHERE u.id = ou.id
`)
	return result.RowsAffected, result.Error
}
