CREATE TABLE IF NOT EXISTS gateway.model_routes (
    id uuid PRIMARY KEY,
    name text NOT NULL CHECK (length(name) BETWEEN 1 AND 128),
    source_model text NOT NULL CHECK (length(source_model) BETWEEN 1 AND 512),
    target_model text NOT NULL CHECK (length(target_model) BETWEEN 1 AND 512),
    provider_id uuid NOT NULL REFERENCES gateway.providers(id) ON DELETE CASCADE,
    weight integer NOT NULL DEFAULT 100 CHECK (weight BETWEEN 1 AND 10000),
    priority integer NOT NULL DEFAULT 100 CHECK (priority BETWEEN -100000 AND 100000),
    conditions jsonb NOT NULL DEFAULT '{}'::jsonb,
    enabled boolean NOT NULL DEFAULT true,
    created_by uuid REFERENCES gateway.admin_accounts(id),
    created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
    updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
    UNIQUE (source_model, provider_id, target_model, priority, conditions)
);

CREATE INDEX IF NOT EXISTS model_routes_lookup_idx
    ON gateway.model_routes (source_model, enabled, priority DESC);

COMMENT ON COLUMN gateway.model_routes.conditions IS
    'Extensible route predicates; initial runtime supports endpoint, API key and tenant matching.';
