#!/usr/bin/env bash
set -euo pipefail

BARON_CONTAINER="${BARON_CONTAINER:-baron_postgres}"
BARON_DB_USER="${BARON_DB_USER:-baron}"
BARON_DB_NAME="${BARON_DB_NAME:-baron_sso}"
KRATOS_CONTAINER="${KRATOS_CONTAINER:-ory_postgres}"
KRATOS_DB_USER="${KRATOS_DB_USER:-ory}"
KRATOS_DB_NAME="${KRATOS_DB_NAME:-ory_kratos}"

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

docker exec -i "${BARON_CONTAINER}" \
	psql -U "${BARON_DB_USER}" -d "${BARON_DB_NAME}" \
	< "${script_dir}/clear_orphan_user_tenant_memberships.sql"

active_tenant_refs="$(
	docker exec "${BARON_CONTAINER}" psql -U "${BARON_DB_USER}" -d "${BARON_DB_NAME}" -At -F $'\t' \
		-c "SELECT id, LOWER(slug) FROM tenants WHERE deleted_at IS NULL ORDER BY id"
)"

docker exec -i "${KRATOS_CONTAINER}" psql -U "${KRATOS_DB_USER}" -d "${KRATOS_DB_NAME}" <<SQL
BEGIN;

CREATE TEMP TABLE active_tenant_refs (
	id text NOT NULL,
	slug text NOT NULL
) ON COMMIT DROP;

COPY active_tenant_refs (id, slug) FROM STDIN WITH (FORMAT text, DELIMITER E'\t');
${active_tenant_refs}
\.

WITH orphan_identities AS (
	SELECT
		i.id,
		i.traits->>'email' AS email,
		i.traits->>'tenant_id' AS tenant_id,
		i.traits->>'companyCode' AS company_code,
		i.traits->'companyCodes' AS company_codes
	FROM identities AS i
	WHERE (
		COALESCE(i.traits->>'tenant_id', '') <> ''
		AND NOT EXISTS (
			SELECT 1
			FROM active_tenant_refs AS refs
			WHERE refs.id = i.traits->>'tenant_id'
		)
	)
	OR (
		COALESCE(i.traits->>'companyCode', '') <> ''
		AND NOT EXISTS (
			SELECT 1
			FROM active_tenant_refs AS refs
			WHERE refs.slug = LOWER(BTRIM(i.traits->>'companyCode'))
		)
	)
	OR EXISTS (
		SELECT 1
		FROM JSONB_ARRAY_ELEMENTS_TEXT(COALESCE(i.traits->'companyCodes', '[]'::jsonb)) AS code(value)
		WHERE NULLIF(BTRIM(code.value), '') IS NOT NULL
		  AND NOT EXISTS (
			SELECT 1
			FROM active_tenant_refs AS refs
			WHERE refs.slug = LOWER(BTRIM(code.value))
		)
	)
),
updated_identities AS (
	UPDATE identities AS i
	SET traits = i.traits - 'tenant_id' - 'companyCode' - 'companyCodes',
		updated_at = NOW()
	FROM orphan_identities AS oi
	WHERE i.id = oi.id
	RETURNING
		i.id,
		oi.email,
		oi.tenant_id AS cleared_tenant_id,
		oi.company_code AS cleared_company_code,
		oi.company_codes AS cleared_company_codes
)
SELECT *
FROM updated_identities
ORDER BY email;

COMMIT;
SQL
