CREATE TABLE IF NOT EXISTS system_settings (
  setting_key text PRIMARY KEY,
  value jsonb NOT NULL DEFAULT '{}'::jsonb,
  created_at timestamptz NOT NULL DEFAULT now(),
  updated_at timestamptz NOT NULL DEFAULT now()
);

INSERT INTO system_settings (setting_key, value)
VALUES (
  'file_storage',
  '{"resultUploadPolicy": "default"}'::jsonb
)
ON CONFLICT (setting_key) DO NOTHING;

CREATE TABLE IF NOT EXISTS file_storage_channels (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  channel_key text NOT NULL UNIQUE,
  name text NOT NULL,
  provider text NOT NULL DEFAULT 'server_main_openapi',
  upload_url text,
  credentials jsonb NOT NULL DEFAULT '{}'::jsonb,
  config jsonb NOT NULL DEFAULT '{}'::jsonb,
  retry_policy jsonb NOT NULL DEFAULT '{
    "enabled": true,
    "maxRetries": 3,
    "backoffSeconds": [60, 120, 180],
    "strategy": "exponential"
  }'::jsonb,
  priority integer NOT NULL DEFAULT 100,
  status text NOT NULL DEFAULT 'disabled',
  last_error text,
  last_failed_at timestamptz,
  last_succeeded_at timestamptz,
  created_at timestamptz NOT NULL DEFAULT now(),
  updated_at timestamptz NOT NULL DEFAULT now(),
  deleted_at timestamptz
);

ALTER TABLE IF EXISTS file_storage_channels
  ADD COLUMN IF NOT EXISTS upload_url text,
  ADD COLUMN IF NOT EXISTS config jsonb NOT NULL DEFAULT '{}'::jsonb,
  ADD COLUMN IF NOT EXISTS retry_policy jsonb NOT NULL DEFAULT '{
    "enabled": true,
    "maxRetries": 3,
    "backoffSeconds": [60, 120, 180],
    "strategy": "exponential"
  }'::jsonb,
  ADD COLUMN IF NOT EXISTS priority integer NOT NULL DEFAULT 100,
  ADD COLUMN IF NOT EXISTS last_error text,
  ADD COLUMN IF NOT EXISTS last_failed_at timestamptz,
  ADD COLUMN IF NOT EXISTS last_succeeded_at timestamptz,
  ADD COLUMN IF NOT EXISTS deleted_at timestamptz;

CREATE INDEX IF NOT EXISTS idx_file_storage_channels_active
  ON file_storage_channels (status, priority, created_at)
  WHERE deleted_at IS NULL;

INSERT INTO file_storage_channels (
  channel_key,
  name,
  provider,
  upload_url,
  credentials,
  config,
  retry_policy,
  priority,
  status
)
VALUES (
  'server-main-openapi',
  'server-main OpenAPI',
  'server_main_openapi',
  'http://127.0.0.1:3001/v1/files/upload',
  '{}'::jsonb,
  '{"scenes": ["upload", "image_result"]}'::jsonb,
  '{
    "enabled": true,
    "maxRetries": 3,
    "backoffSeconds": [60, 120, 180],
    "strategy": "exponential"
  }'::jsonb,
  100,
  'disabled'
)
ON CONFLICT (channel_key) DO NOTHING;
