CREATE EXTENSION IF NOT EXISTS pgcrypto;

INSERT INTO gateway_user_groups (
  group_key, name, description, priority,
  recharge_discount_policy, billing_discount_policy, rate_limit_policy, quota_policy, metadata, status
)
VALUES
  (
    'default', 'Default Users', 'Built-in default group for local and synchronized users.', 100,
    '{"discountFactor":1}'::jsonb,
    '{"discountFactor":1}'::jsonb,
    '{"rules":[{"metric":"rpm","limit":60,"windowSeconds":60},{"metric":"tpm_total","limit":120000,"windowSeconds":60},{"metric":"concurrent","limit":3,"leaseTtlSeconds":120}]}'::jsonb,
    '{}'::jsonb,
    '{"seed":"phase1"}'::jsonb,
    'active'
  ),
  (
    'vip', 'VIP Users', 'Higher quota group for future recharge and concurrency policies.', 50,
    '{"discountFactor":0.9}'::jsonb,
    '{"discountFactor":0.95}'::jsonb,
    '{"rules":[{"metric":"rpm","limit":300,"windowSeconds":60},{"metric":"tpm_total","limit":600000,"windowSeconds":60},{"metric":"concurrent","limit":10,"leaseTtlSeconds":120}]}'::jsonb,
    '{}'::jsonb,
    '{"seed":"phase1"}'::jsonb,
    'active'
  )
ON CONFLICT (group_key) DO UPDATE
SET name = EXCLUDED.name,
    description = EXCLUDED.description,
    priority = EXCLUDED.priority,
    recharge_discount_policy = EXCLUDED.recharge_discount_policy,
    billing_discount_policy = EXCLUDED.billing_discount_policy,
    rate_limit_policy = EXCLUDED.rate_limit_policy,
    updated_at = now();

INSERT INTO gateway_tenants (tenant_key, source, external_tenant_id, name, default_user_group_id, metadata, status)
VALUES (
  'default',
  'gateway',
  'default',
  'Default Tenant',
  (SELECT id FROM gateway_user_groups WHERE group_key = 'default'),
  '{"seed":"phase1"}'::jsonb,
  'active'
)
ON CONFLICT (tenant_key) DO UPDATE
SET name = EXCLUDED.name,
    default_user_group_id = EXCLUDED.default_user_group_id,
    updated_at = now();

INSERT INTO model_catalog_providers (
  provider_key, provider_code, display_name, provider_type, icon_path, source, capability_schema, default_rate_limit_policy, metadata, status
)
VALUES
  (
    'openai',
    'openai',
    'OpenAI',
    'openai',
    NULL,
    'server-main.integration-platform',
    '{"chat":true,"imageGeneration":true,"imageEdit":true,"stream":true}'::jsonb,
    '{"rules":[{"metric":"rpm","limit":500,"windowSeconds":60},{"metric":"tpm_total","limit":1000000,"windowSeconds":60},{"metric":"concurrent","limit":20,"leaseTtlSeconds":120}]}'::jsonb,
    '{"seed":"phase1","syncSource":"server-main.integration-platform","sourceCode":"openai"}'::jsonb,
    'active'
  ),
  (
    'gemini',
    'google-gemini',
    'Google Gemini',
    'gemini',
    'https://static.51easyai.com/gemini-color.png',
    'server-main.integration-platform',
    '{"chat":true,"imageGeneration":true,"imageEdit":true,"stream":true}'::jsonb,
    '{"rules":[{"metric":"rpm","limit":500,"windowSeconds":60},{"metric":"tpm_total","limit":1000000,"windowSeconds":60},{"metric":"concurrent","limit":20,"leaseTtlSeconds":120}]}'::jsonb,
    '{"seed":"phase1","syncSource":"server-main.integration-platform","sourceCode":"google-gemini"}'::jsonb,
    'active'
  )
ON CONFLICT (provider_key) DO UPDATE
SET provider_code = EXCLUDED.provider_code,
    display_name = EXCLUDED.display_name,
    provider_type = EXCLUDED.provider_type,
    icon_path = EXCLUDED.icon_path,
    source = EXCLUDED.source,
    capability_schema = EXCLUDED.capability_schema,
    default_rate_limit_policy = EXCLUDED.default_rate_limit_policy,
    metadata = model_catalog_providers.metadata || EXCLUDED.metadata,
    updated_at = now();

INSERT INTO base_model_catalog (
  provider_id, provider_key, canonical_model_key, provider_model_name, model_type, display_name,
  capabilities, base_billing_config, default_rate_limit_policy, metadata, status
)
VALUES
  (
    (SELECT id FROM model_catalog_providers WHERE provider_key = 'openai'),
    'openai',
    'openai:gpt-4o-mini',
    'gpt-4o-mini',
    'chat',
    'GPT-4o mini',
    '{"stream":true,"vision":true,"inputModalities":["text","image"],"outputModalities":["text"],"maxInputTokens":128000}'::jsonb,
    '{"textInputPer1k":0.15,"textOutputPer1k":0.6,"currency":"resource"}'::jsonb,
    '{"rules":[{"metric":"rpm","limit":300,"windowSeconds":60},{"metric":"tpm_total","limit":500000,"windowSeconds":60},{"metric":"concurrent","limit":10,"leaseTtlSeconds":120}]}'::jsonb,
    '{"seed":"phase1"}'::jsonb,
    'active'
  ),
  (
    (SELECT id FROM model_catalog_providers WHERE provider_key = 'openai'),
    'openai',
    'openai:gpt-image-1',
    'gpt-image-1',
    'image',
    'GPT Image 1',
    '{"imageGeneration":true,"imageEdit":true,"inputModalities":["text","image","mask"],"outputModalities":["image"],"sizes":["1024x1024","1024x1536","1536x1024"],"qualities":["low","medium","high"]}'::jsonb,
    '{"imageBase":5,"editBase":6,"currency":"resource","qualityWeights":{"low":0.7,"standard":1,"medium":1,"high":1.4},"sizeWeights":{"1024x1024":1,"1024x1536":1.35,"1536x1024":1.35}}'::jsonb,
    '{"rules":[{"metric":"rpm","limit":60,"windowSeconds":60},{"metric":"concurrent","limit":4,"leaseTtlSeconds":180}]}'::jsonb,
    '{"seed":"phase1"}'::jsonb,
    'active'
  ),
  (
    (SELECT id FROM model_catalog_providers WHERE provider_key = 'gemini'),
    'gemini',
    'gemini:gemini-2.5-flash',
    'gemini-2.5-flash',
    'chat',
    'Gemini 2.5 Flash',
    '{"stream":true,"vision":true,"inputModalities":["text","image"],"outputModalities":["text"],"maxInputTokens":1048576}'::jsonb,
    '{"textInputPer1k":0.1,"textOutputPer1k":0.4,"currency":"resource"}'::jsonb,
    '{"rules":[{"metric":"rpm","limit":300,"windowSeconds":60},{"metric":"tpm_total","limit":500000,"windowSeconds":60},{"metric":"concurrent","limit":10,"leaseTtlSeconds":120}]}'::jsonb,
    '{"seed":"phase1"}'::jsonb,
    'active'
  ),
  (
    (SELECT id FROM model_catalog_providers WHERE provider_key = 'gemini'),
    'gemini',
    'gemini:gemini-2.5-flash-image',
    'gemini-2.5-flash-image',
    'image',
    'Gemini 2.5 Flash Image',
    '{"imageGeneration":true,"imageEdit":true,"inputModalities":["text","image","mask"],"outputModalities":["image"],"sizes":["1024x1024","1024x1536","1536x1024"],"qualities":["standard","high"]}'::jsonb,
    '{"imageBase":4,"editBase":5,"currency":"resource","qualityWeights":{"standard":1,"high":1.35},"sizeWeights":{"1024x1024":1,"1024x1536":1.3,"1536x1024":1.3}}'::jsonb,
    '{"rules":[{"metric":"rpm","limit":60,"windowSeconds":60},{"metric":"concurrent","limit":4,"leaseTtlSeconds":180}]}'::jsonb,
    '{"seed":"phase1"}'::jsonb,
    'active'
  )
ON CONFLICT (canonical_model_key) DO UPDATE
SET provider_id = EXCLUDED.provider_id,
    provider_key = EXCLUDED.provider_key,
    provider_model_name = EXCLUDED.provider_model_name,
    model_type = EXCLUDED.model_type,
    display_name = EXCLUDED.display_name,
    capabilities = EXCLUDED.capabilities,
    base_billing_config = EXCLUDED.base_billing_config,
    default_rate_limit_policy = EXCLUDED.default_rate_limit_policy,
    updated_at = now();

INSERT INTO integration_platforms (
  provider, platform_key, name, base_url, auth_type, credentials, config,
  default_pricing_mode, default_discount_factor, retry_policy, rate_limit_policy, priority, status
)
VALUES
  (
    'openai', 'openai-simulation', 'OpenAI Simulation',
    'https://api.openai.com/v1', 'bearer',
    '{"mode":"simulation"}'::jsonb,
    '{"testMode":true,"seed":"phase1"}'::jsonb,
    'inherit_discount', 1,
    '{"enabled":true,"maxAttempts":2,"retryOn":["rate_limit","timeout","server_error","network"]}'::jsonb,
    '{"rules":[{"metric":"rpm","limit":120,"windowSeconds":60},{"metric":"tpm_total","limit":240000,"windowSeconds":60},{"metric":"concurrent","limit":6,"leaseTtlSeconds":120}]}'::jsonb,
    900,
    'enabled'
  ),
  (
    'gemini', 'gemini-simulation', 'Gemini Simulation',
    'https://generativelanguage.googleapis.com', 'api_key',
    '{"mode":"simulation"}'::jsonb,
    '{"testMode":true,"seed":"phase1"}'::jsonb,
    'inherit_discount', 1,
    '{"enabled":true,"maxAttempts":2,"retryOn":["rate_limit","timeout","server_error","network"]}'::jsonb,
    '{"rules":[{"metric":"rpm","limit":120,"windowSeconds":60},{"metric":"tpm_total","limit":240000,"windowSeconds":60},{"metric":"concurrent","limit":6,"leaseTtlSeconds":120}]}'::jsonb,
    910,
    'enabled'
  )
ON CONFLICT (platform_key) DO UPDATE
SET name = EXCLUDED.name,
    base_url = EXCLUDED.base_url,
    auth_type = EXCLUDED.auth_type,
    credentials = EXCLUDED.credentials,
    config = EXCLUDED.config,
    default_pricing_mode = EXCLUDED.default_pricing_mode,
    default_discount_factor = EXCLUDED.default_discount_factor,
    retry_policy = EXCLUDED.retry_policy,
    rate_limit_policy = EXCLUDED.rate_limit_policy,
    priority = EXCLUDED.priority,
    status = EXCLUDED.status,
    updated_at = now();

INSERT INTO platform_models (
  platform_id, base_model_id, model_name, model_alias, model_type, display_name,
  capabilities, pricing_mode, billing_config, retry_policy, rate_limit_policy, enabled
)
SELECT p.id, b.id, b.provider_model_name, b.canonical_model_key,
       CASE b.model_type
         WHEN 'chat' THEN '["text_generate"]'::jsonb
         WHEN 'text' THEN '["text_generate"]'::jsonb
         WHEN 'responses' THEN '["text_generate"]'::jsonb
         WHEN 'image' THEN '["image_generate","image_edit"]'::jsonb
         WHEN 'images.generations' THEN '["image_generate"]'::jsonb
         WHEN 'images.edits' THEN '["image_edit"]'::jsonb
         WHEN 'video' THEN '["video_generate"]'::jsonb
         WHEN 'videos.generations' THEN '["video_generate"]'::jsonb
         ELSE jsonb_build_array(b.model_type)
       END,
       b.display_name,
       b.capabilities, 'inherit_discount', b.base_billing_config,
       '{"enabled":true,"maxAttempts":2}'::jsonb,
       b.default_rate_limit_policy,
       true
FROM integration_platforms p
JOIN base_model_catalog b ON b.provider_key = p.provider
WHERE p.platform_key IN ('openai-simulation', 'gemini-simulation')
ON CONFLICT (platform_id, model_name) DO UPDATE
SET base_model_id = EXCLUDED.base_model_id,
    model_alias = EXCLUDED.model_alias,
    display_name = EXCLUDED.display_name,
    capabilities = EXCLUDED.capabilities,
    pricing_mode = EXCLUDED.pricing_mode,
    billing_config = EXCLUDED.billing_config,
    retry_policy = EXCLUDED.retry_policy,
    rate_limit_policy = EXCLUDED.rate_limit_policy,
    enabled = EXCLUDED.enabled,
    updated_at = now();

INSERT INTO model_pricing_rules (scope_type, scope_id, resource_type, unit, base_price, currency, base_weight, dynamic_weight)
SELECT 'base_model', b.id, item.resource_type, item.unit, item.base_price, 'resource', item.base_weight, item.dynamic_weight
FROM base_model_catalog b
JOIN (
  VALUES
    ('openai:gpt-4o-mini', 'text_input', '1k_tokens', 0.15::numeric, '{}'::jsonb, '{}'::jsonb),
    ('openai:gpt-4o-mini', 'text_output', '1k_tokens', 0.60::numeric, '{}'::jsonb, '{}'::jsonb),
    ('openai:gpt-image-1', 'image', 'image', 5.00::numeric, '{"mode":"generation"}'::jsonb, '{"quality":true,"size":true}'::jsonb),
    ('openai:gpt-image-1', 'image_edit', 'image', 6.00::numeric, '{"mode":"edit"}'::jsonb, '{"quality":true,"size":true}'::jsonb),
    ('gemini:gemini-2.5-flash', 'text_input', '1k_tokens', 0.10::numeric, '{}'::jsonb, '{}'::jsonb),
    ('gemini:gemini-2.5-flash', 'text_output', '1k_tokens', 0.40::numeric, '{}'::jsonb, '{}'::jsonb),
    ('gemini:gemini-2.5-flash-image', 'image', 'image', 4.00::numeric, '{"mode":"generation"}'::jsonb, '{"quality":true,"size":true}'::jsonb),
    ('gemini:gemini-2.5-flash-image', 'image_edit', 'image', 5.00::numeric, '{"mode":"edit"}'::jsonb, '{"quality":true,"size":true}'::jsonb)
) AS item(canonical_model_key, resource_type, unit, base_price, base_weight, dynamic_weight)
  ON item.canonical_model_key = b.canonical_model_key
WHERE NOT EXISTS (
  SELECT 1
  FROM model_pricing_rules existing
  WHERE existing.scope_type = 'base_model'
    AND existing.scope_id = b.id
    AND existing.resource_type = item.resource_type
    AND existing.unit = item.unit
);
