-- mockshot-nuke.sql — exact reversal of mockshot-seed.sql, FK order.
BEGIN;

DELETE FROM core.pool_provisions
WHERE grant_id IN (SELECT grant_id FROM core.grants WHERE description = 'mockshot');

DELETE FROM core.grants WHERE description = 'mockshot';

DELETE FROM core.payments
WHERE billing_account_id IN
      (SELECT billing_account_id FROM core.accounts WHERE metadata @> '{"mockshot": true}'::jsonb);

DELETE FROM core.invoices
WHERE billing_account_id IN
      (SELECT billing_account_id FROM core.accounts WHERE metadata @> '{"mockshot": true}'::jsonb);

DELETE FROM core.pool_provisions
WHERE subscription_id IN
      (SELECT s.subscription_id FROM core.subscriptions s
       JOIN core.accounts a ON a.billing_account_id = s.billing_account_id
       WHERE a.metadata @> '{"mockshot": true}'::jsonb);

DELETE FROM core.subscription_items
WHERE subscription_id IN
      (SELECT s.subscription_id FROM core.subscriptions s
       JOIN core.accounts a ON a.billing_account_id = s.billing_account_id
       WHERE a.metadata @> '{"mockshot": true}'::jsonb);

DELETE FROM core.subscriptions
WHERE billing_account_id IN
      (SELECT billing_account_id FROM core.accounts WHERE metadata @> '{"mockshot": true}'::jsonb);

DELETE FROM core.accounts WHERE metadata @> '{"mockshot": true}'::jsonb;

-- After the subscription_items delete above (items reference prices), and
-- prices before their products.
DELETE FROM core.prices
WHERE product_id IN (SELECT product_id FROM core.products WHERE metadata @> '{"mockshot": true}'::jsonb);

-- After BOTH provision deletes above — grant-sourced and subscription-
-- sourced provisions each reference mock products.
DELETE FROM core.products WHERE metadata @> '{"mockshot": true}'::jsonb;

DELETE FROM core.organizations WHERE slug LIKE 'mockshot-%';

-- After the organizations delete (orgs reference the type).
DELETE FROM core.org_types WHERE org_type = 'team' AND description = 'mockshot';

-- Cascades the mock persons (fk_persons_user_id ON DELETE CASCADE)
DELETE FROM core.users WHERE oidc_subject LIKE 'mockshot-sub-%';

COMMIT;

-- Should all be zero
SELECT (SELECT count(*) FROM core.users WHERE oidc_subject LIKE 'mockshot-sub-%')      AS users_left,
       (SELECT count(*) FROM core.organizations WHERE slug LIKE 'mockshot-%')          AS orgs_left,
       (SELECT count(*) FROM core.grants WHERE description = 'mockshot')               AS grants_left,
       (SELECT count(*) FROM core.accounts WHERE metadata @> '{"mockshot": true}'::jsonb) AS accounts_left;
