-- 삭제되었거나 존재하지 않는 tenant를 가리키는 사용자 소속정보를 정리한다.
-- 실행 예:
--   docker exec -i baron_postgres psql -U baron -d baron_sso < scripts/clear_orphan_user_tenant_memberships.sql

BEGIN;

WITH orphan_users AS (
	SELECT
		u.id,
		u.email,
		u.tenant_id,
		u.company_code,
		u.company_codes
	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
			)
		)
		OR (
			NULLIF(BTRIM(u.company_code), '') IS NOT NULL
			AND NOT EXISTS (
				SELECT 1
				FROM tenants AS t
				WHERE LOWER(t.slug) = LOWER(BTRIM(u.company_code))
				  AND t.deleted_at IS NULL
			)
		)
		OR EXISTS (
			SELECT 1
			FROM UNNEST(COALESCE(u.company_codes, ARRAY[]::text[])) AS code(value)
			WHERE NULLIF(BTRIM(code.value), '') IS NOT NULL
			  AND NOT EXISTS (
				SELECT 1
				FROM tenants AS t
				WHERE LOWER(t.slug) = LOWER(BTRIM(code.value))
				  AND t.deleted_at IS NULL
			  )
		)
	  )
),
updated_users AS (
	UPDATE users AS u
	SET tenant_id = NULL,
		company_code = '',
		company_codes = NULL,
		updated_at = NOW()
	FROM orphan_users AS ou
	WHERE u.id = ou.id
	RETURNING
		u.id,
		u.email,
		ou.tenant_id AS cleared_tenant_id,
		ou.company_code AS cleared_company_code,
		ou.company_codes AS cleared_company_codes
)
SELECT *
FROM updated_users
ORDER BY email;

COMMIT;
