ALTER TABLE tenant_monitoring_quotas
    ADD COLUMN IF NOT EXISTS workspace_id BIGINT REFERENCES workspaces(id);

UPDATE tenant_monitoring_quotas q
SET workspace_id = w.id
FROM workspaces w
WHERE w.tenant_id = q.tenant_id
  AND w.is_default = TRUE
  AND q.workspace_id IS NULL;

ALTER TABLE tenant_monitoring_quotas
    ALTER COLUMN workspace_id SET NOT NULL;

CREATE INDEX IF NOT EXISTS idx_monitoring_quotas_workspace
    ON tenant_monitoring_quotas (workspace_id);

ALTER TABLE platform_accounts
    ADD COLUMN IF NOT EXISTS workspace_id BIGINT REFERENCES workspaces(id);

UPDATE platform_accounts a
SET workspace_id = w.id
FROM workspaces w
WHERE w.tenant_id = a.tenant_id
  AND w.is_default = TRUE
  AND a.workspace_id IS NULL;

ALTER TABLE platform_accounts
    ALTER COLUMN workspace_id SET NOT NULL;

CREATE INDEX IF NOT EXISTS idx_platform_accounts_workspace
    ON platform_accounts (workspace_id);
