CREATE TABLE IF NOT EXISTS platform.public_embed_widgets (
    widget_id TEXT PRIMARY KEY,
    widget_public_key TEXT NOT NULL UNIQUE,
    business_id VARCHAR(100) NOT NULL,
    assistant_id TEXT NOT NULL DEFAULT 'opi',
    assistant_endpoint_id TEXT NOT NULL,
    sucursal_id_default INTEGER NULL,
    identity_mode TEXT NOT NULL DEFAULT 'anonymous',
    theme_json JSONB NOT NULL DEFAULT '{}'::jsonb,
    features_json JSONB NOT NULL DEFAULT '{}'::jsonb,
    rate_limit_profile JSONB NOT NULL DEFAULT '{}'::jsonb,
    status TEXT NOT NULL DEFAULT 'draft',
    rollout_stage_override TEXT NULL,
    metadata_json JSONB NOT NULL DEFAULT '{}'::jsonb,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CONSTRAINT public_embed_widgets_identity_mode_chk
        CHECK (identity_mode IN ('anonymous', 'optional_authenticated', 'required_authenticated')),
    CONSTRAINT public_embed_widgets_status_chk
        CHECK (status IN ('draft', 'internal', 'canary', 'live', 'read_only', 'disabled', 'revoked'))
);

CREATE INDEX IF NOT EXISTS public_embed_widgets_business_id_idx
    ON platform.public_embed_widgets (business_id);

CREATE INDEX IF NOT EXISTS public_embed_widgets_assistant_endpoint_id_idx
    ON platform.public_embed_widgets (assistant_endpoint_id);

CREATE INDEX IF NOT EXISTS public_embed_widgets_status_idx
    ON platform.public_embed_widgets (status);

CREATE TABLE IF NOT EXISTS platform.public_embed_widget_allowed_origins (
    id BIGSERIAL PRIMARY KEY,
    widget_id TEXT NOT NULL REFERENCES platform.public_embed_widgets(widget_id) ON DELETE CASCADE,
    origin TEXT NOT NULL,
    status TEXT NOT NULL DEFAULT 'active',
    notes TEXT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CONSTRAINT public_embed_widget_allowed_origins_status_chk
        CHECK (status IN ('active', 'disabled')),
    CONSTRAINT public_embed_widget_allowed_origins_widget_origin_uniq
        UNIQUE (widget_id, origin)
);

CREATE INDEX IF NOT EXISTS public_embed_widget_allowed_origins_widget_id_idx
    ON platform.public_embed_widget_allowed_origins (widget_id);

CREATE INDEX IF NOT EXISTS public_embed_widget_allowed_origins_status_idx
    ON platform.public_embed_widget_allowed_origins (status);
