# Database Migration: Enhanced Search Function

This migration updates the `search_sojorn()` function to enable full-text search across posts, users, and hashtags.

## What Changed

The search function now searches:
- **Users**: by handle AND display name (previously only handle)
- **Tags**: hashtags from the posts.tags array (unchanged)
- **Posts**: NEW - searches post body content for any word, matching hashtags

## Option 1: Apply via Supabase Dashboard (Recommended)

1. Go to your Supabase Dashboard: https://app.supabase.com/project/zwkihedetedlatyvplyz

2. Navigate to **SQL Editor** in the left sidebar

3. Click **"New Query"**

4. Copy and paste the SQL from `supabase/migrations/update_search_function.sql`

5. Click **"Run"** to execute the migration

6. Verify success - you should see "Success. No rows returned"

## Option 2: Apply via Supabase CLI

If you have Supabase CLI configured with your project:

```bash
# Link to your project (if not already linked)
supabase link --project-ref zwkihedetedlatyvplyz

# Push the migration
supabase db push --include-all
```

## Verification

After applying the migration, test the search:

1. Open the app and navigate to Search
2. Try searching for:
   - A username (e.g., "john")
   - A hashtag (e.g., "#nature")
   - Any word from a post body (e.g., "wellness")
3. Click on a hashtag in a post - it should navigate to search with results

## Rollback (if needed)

If you need to revert, run this SQL:

```sql
CREATE OR REPLACE FUNCTION search_sojorn(p_query TEXT, limit_count INTEGER DEFAULT 10)
RETURNS JSON LANGUAGE plpgsql STABLE AS $$
DECLARE result JSON;
BEGIN
    SELECT json_build_object(
        'users', (SELECT json_agg(json_build_object('id', p.id, 'username', p.handle, 'display_name', p.display_name, 'avatar_url', p.avatar_url, 'harmony_tier', COALESCE(ts.tier, 'new')))
            FROM profiles p LEFT JOIN trust_state ts ON p.id = ts.user_id WHERE p.handle ILIKE '%' || p_query || '%' LIMIT limit_count),
        'tags', (SELECT json_agg(json_build_object('tag', tag, 'count', cnt)) FROM (
            SELECT LOWER(UNNEST(tags)) AS tag, COUNT(*) AS cnt FROM posts WHERE tags IS NOT NULL AND deleted_at IS NULL
            GROUP BY tag HAVING LOWER(tag) LIKE '%' || LOWER(p_query) || '%' ORDER BY cnt DESC LIMIT limit_count) t)
    ) INTO result;
    RETURN result;
END;
$$;
```

Note: This removes the posts search capability.
