-- Align factory AI quotas with reasonable SME defaults (per user, org keys).
-- Only touch rows still at the previous factory values.

UPDATE ai_cost_policies
SET daily_limit_micro_eur = 2000000,
    monthly_limit_micro_eur = 35000000,
    updated_at = NOW()
WHERE scope_type = 'org'
  AND daily_limit_micro_eur = 10000000
  AND monthly_limit_micro_eur = 100000000;

UPDATE org_settings
SET settings = jsonb_set(
    jsonb_set(
        jsonb_set(
            jsonb_set(
                jsonb_set(
                    jsonb_set(
                        jsonb_set(
                            COALESCE(settings, '{}'::jsonb),
                            '{usage_quotas,llm_daily_cost_limit_eur}',
                            '2'::jsonb
                        ),
                        '{usage_quotas,llm_monthly_cost_limit_eur}',
                        '35'::jsonb
                    ),
                    '{usage_quotas,llm_requests_per_day}',
                    '75'::jsonb
                ),
                '{usage_quotas,llm_tokens_per_month}',
                '2000000'::jsonb
            ),
            '{usage_quotas,search_requests_per_day}',
            '20'::jsonb
        ),
        '{usage_quotas,max_api_tokens_per_user}',
        '5'::jsonb
    ),
    '{usage_quotas,max_webhooks_per_user}',
    '5'::jsonb
),
updated_at = NOW()
WHERE id = 1
  AND (
    settings->'usage_quotas' IS NULL
    OR settings->'usage_quotas' = 'null'::jsonb
    OR (
      COALESCE((settings->'usage_quotas'->>'llm_daily_cost_limit_eur')::numeric, 10) = 10
      AND COALESCE((settings->'usage_quotas'->>'llm_monthly_cost_limit_eur')::numeric, 100) = 100
      AND COALESCE((settings->'usage_quotas'->>'llm_requests_per_day')::numeric, 100) = 100
      AND COALESCE((settings->'usage_quotas'->>'llm_tokens_per_month')::numeric, 500000) = 500000
      AND COALESCE((settings->'usage_quotas'->>'search_requests_per_day')::numeric, 50) = 50
      AND COALESCE((settings->'usage_quotas'->>'max_api_tokens_per_user')::numeric, 10) = 10
      AND COALESCE((settings->'usage_quotas'->>'max_webhooks_per_user')::numeric, 20) = 20
    )
  );
