-- Step 1: Recreate search_cache table based on new robust spec
DROP TABLE IF EXISTS search_cache;

CREATE TABLE search_cache (
    query_key TEXT PRIMARY KEY, -- sha256(kind + "|" + query_norm)
    query_raw TEXT NOT NULL,
    query_norm TEXT NOT NULL,
    kind TEXT NOT NULL CHECK (kind IN ('products', 'opportunities')),
    results JSONB DEFAULT '[]'::jsonb,
    sources JSONB DEFAULT '[]'::jsonb,
    fetched_at TIMESTAMPTZ DEFAULT NOW(),
    expires_at TIMESTAMPTZ NOT NULL
);

-- Indexes for performance
CREATE INDEX idx_search_cache_query_norm ON search_cache(query_norm);
CREATE INDEX idx_search_cache_expires_at ON search_cache(expires_at);

-- RLS Policy (Open for backend/service role, read-only for anon if needed, but mainly managed by function)
ALTER TABLE search_cache ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Enable read/write for service role" ON search_cache
    USING (true)
    WITH CHECK (true);

CREATE POLICY "Enable read for authenticated users" ON search_cache
    FOR SELECT
    TO authenticated
    USING (true);
