# Deployment Guide

## Prerequisites

1. **Neon Database**
   - Ensure your Neon database is set up and running
   - Run all migration scripts in order:
     - `scripts/seed-database.sql`
     - `scripts/06-add-verification-requests.sql`
     - `scripts/07-add-followed-artists-table.sql`
     - `scripts/08-add-artist-earnings-constraint.sql`

2. **Vercel Blob Storage**
   - Connected and configured in your Vercel project
   - `BLOB_READ_WRITE_TOKEN` environment variable set

3. **Environment Variables**
   - Copy `.env.example` to `.env.local` for local development
   - Set all required environment variables in Vercel project settings

## Environment Variables Required

```bash
DATABASE_URL=                    # Neon connection string
BLOB_READ_WRITE_TOKEN=          # Vercel Blob token
NEXT_PUBLIC_APP_URL=            # Your production URL
R2_PUBLIC_URL=                 # R2 public URL for cover images
```

## Deployment Steps

### 1. Local Testing

```bash
# Install dependencies
npm install

# Run development server
npm run dev

# Build for production
npm run build

# Test production build locally
npm start
```

### 2. Deploy to Vercel

```bash
# Install Vercel CLI
npm i -g vercel

# Login to Vercel
vercel login

# Deploy
vercel --prod
```

### 3. Post-Deployment

1. **Verify Database Connection**
   - Check that all API routes connect successfully
   - Test user authentication flows

2. **Test Core Features**
   - User registration and login
   - Music upload and playback
   - Playlist creation
   - Download functionality
   - Artist verification

3. **Monitor Performance**
   - Check Vercel Analytics dashboard
   - Monitor database query performance in Neon
   - Review error logs

## PWA Features

The app includes PWA support with:
- Service worker for offline functionality
- Manifest for installable app
- Background audio playback
- Download tracks for offline use

**Note:** PWA features only work in production builds with HTTPS.

## Troubleshooting

### Database Connection Issues
- Verify `DATABASE_URL` is correct
- Check Neon database is active
- Ensure IP allowlist includes Vercel IPs (if configured)

### Blob Upload Issues  
- Verify `BLOB_READ_WRITE_TOKEN` is set
- Check Blob storage quota
- Review file size limits (100MB max)

### Build Errors
- Run `npm run build` locally first
- Check TypeScript errors
- Verify all dependencies are installed

### Image Display Issues
- Images use native `<img>` tags with fallback handling
- If images don't load, check that `cover_url` fields in database contain valid URLs
- Broken images automatically show gradient backgrounds with music icons
- Verify Blob storage URLs are publicly accessible

### Playlist/Mix Not Found Errors
- Ensure playlist IDs in URLs are valid UUIDs from the database
- Check that playlists exist in the `playlists` table
- Verify user has permission to access private playlists
- App uses `/mix/[id]` route for all playlists
- Database returns 404 for invalid or missing playlist IDs

### Stream Tracking Not Working
- Verify `listening_history` table exists
- Check that player provider is recording streams via `/api/history`
- Ensure artist stats queries are pulling from `listening_history`
- Stream increments happen when a track plays for more than 30 seconds

### PWA Service Worker Issues
- Service workers only register in production (not preview/localhost)
- Clear browser cache if service worker updates aren't applying
- Check browser console for service worker registration errors
- Ensure HTTPS is enabled for PWA features to work

### User Session/Authentication Issues
- User data is isolated by user ID in IndexedDB
- Switching accounts properly clears previous user's data
- If seeing wrong user data, clear browser IndexedDB storage
- Check that `user.id` is being passed correctly to all user-specific APIs

### Cover Image Not Displaying

**Issue:** Track or album cover images show placeholder instead of actual image.

**Solutions:**
1. **Check Database Fields:**
   - Verify `tracks.cover_url` contains valid R2 URLs
   - Check `albums.cover_url` for album covers
   - Run query: `SELECT id, title, cover_url FROM tracks WHERE cover_url IS NOT NULL LIMIT 5`

2. **Verify R2 Configuration:**
   - Ensure `R2_PUBLIC_URL` environment variable is set correctly
   - Test direct URL access: `https://your-r2-url.com/covers/filename.jpg`
   - Check R2 bucket has public read access enabled

3. **Image Loading Priority:**
   - App checks: track.cover_url → track.album_cover → placeholder
   - Console logs show: `[v0] Cover image loaded successfully: [URL]`
   - If URL is undefined, check database query includes cover fields

4. **Common Fixes:**
   ```sql
   -- Update tracks with missing covers to use album cover
   UPDATE tracks t
   SET cover_url = al.cover_url
   FROM albums al
   WHERE t.album_id = al.id AND t.cover_url IS NULL AND al.cover_url IS NOT NULL;
   ```

### Mixtape/Playlist Creation Fails

**Issue:** Users get "Erreur lors de la création" when creating playlists.

**Solutions:**
1. **Check Authentication:**
   - Verify user_id is being passed in request body
   - Check auth token is valid and not expired
   - Console should show: `[v0] Created playlist: {id, name, tracks}`

2. **Validate Track IDs:**
   - Ensure track_ids array contains valid UUIDs
   - Tracks must have status = 'published'
   - Check query: `SELECT id FROM tracks WHERE id = ANY($1) AND status = 'published'`

3. **Database Constraints:**
   - Verify playlists table exists
   - Check playlist_tracks junction table
   - Ensure user_id FK constraint is satisfied

4. **Privacy Settings:**
   - Private playlists (is_public = false) only visible to creator
   - Check WHERE clause: `(p.is_public = TRUE OR p.user_id = $1)`
   - API enforces privacy at query level

### Download Not Working

**Issue:** Users click download but tracks don't appear in downloads page.

**Solutions:**
1. **Check IndexedDB:**
   - Open DevTools → Application → IndexedDB
   - Look for `musique-offline-[userId]` database
   - Verify tracks and audio-files stores exist

2. **Verify Download Flow:**
   ```javascript
   // Track should be downloaded with:
   offlineStorage.downloadTrackForOffline(track)
   // Not just toggling a flag
   ```

3. **Common Issues:**
   - Browser has IndexedDB disabled (private mode)
   - Storage quota exceeded (check with `navigator.storage.estimate()`)
   - Audio fetch fails (check network tab for /api/stream/[id])
   - User not logged in (IndexedDB requires user_id)

4. **Debug Logging:**
   - Console shows: `[v0] [OfflineStorage] Saving track: [title]`
   - Check for: `[v0] [OfflineStorage] Track saved successfully`
   - If missing, check toast notifications for error messages

## Production Checklist

- [ ] All environment variables set in Vercel
- [ ] Database migrations run successfully
- [ ] Blob storage configured and working
- [ ] Authentication flows tested
- [ ] Music upload and playback tested
- [ ] Artist dashboard shows real data
- [ ] Admin panel accessible and functional
- [ ] PWA manifest and service worker configured
- [ ] Analytics tracking enabled
- [ ] Error monitoring set up
- [ ] Cover images loading from R2 correctly
- [ ] Private playlists only visible to owners
- [ ] Download functionality tested offline
- [ ] Track metadata includes cover_url and album_cover
