# 🔧 Firebase Configuration Guide - Production Setup

**Status**: ✅ Ready for Configuration  
**Created**: February 3, 2026

---

## 📋 Firebase Setup Steps

### Step 1: Verify Firebase Console

**Go to**: https://console.firebase.google.com/

**Verify Project**: findvault-55a8e
- ✅ Firestore Database
- ✅ Authentication
- ✅ Hosting
- ✅ Storage
- ✅ Functions (optional)

---

## 🔐 Firestore Security Rules (PRODUCTION)

### Copy-Paste These Rules

**Go to**: Firebase Console → Firestore → Rules

**Replace all with:**

```javascript
rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    
    // ============ PUBLIC COLLECTIONS ============
    
    // Tags - Anyone can read, authenticated users can modify
    match /tags/{tagId} {
      allow read: if true;
      allow create: if request.auth != null;
      allow update, delete: if request.auth.uid == resource.data.ownerId 
                           || request.auth.token.admin == true;
    }
    
    // ============ AUTHENTICATED ONLY ============
    
    // Security Logs - All authenticated users can read/write
    match /security_logs/{logId} {
      allow read: if request.auth != null;
      allow write: if request.auth != null;
    }
    
    // Security Audit - Admin only
    match /security_audit/{auditId} {
      allow read, write: if request.auth.token.admin == true;
    }
    
    // ============ PRIVATE USER DATA ============
    
    // Users - Own profile only
    match /users/{uid} {
      allow read, write: if request.auth.uid == uid;
    }
    
    // Admin Settings - Admin only
    match /admin_settings/{doc=**} {
      allow read, write: if request.auth.token.admin == true;
    }
    
    // Orders - Own orders only
    match /orders/{orderId} {
      allow read: if request.auth.uid == resource.data.userId 
                  || request.auth.token.admin == true;
      allow write: if request.auth.uid == resource.data.userId;
    }
    
    // ============ CATCH-ALL ============
    
    match /{document=**} {
      allow read, write: if false;
    }
  }
}
```

**Click "Publish" ✅**

---

## 📜 Firestore Indexes (PRODUCTION)

### Index 1: Security Logs by Event Type

**Go to**: Firebase Console → Firestore → Indexes → Composite

**Create New Index:**
- Collection: `security_logs`
- Fields: `eventType` (Ascending), `timestamp` (Descending)
- Status: Automatic

### Index 2: Fraud Alerts

**Create New Index:**
- Collection: `security_logs`
- Fields: `eventType` (Ascending) with filter: `potential_fraud_detected`
- Fields: `timestamp` (Descending)

### Index 3: Tags by Owner

**Create New Index:**
- Collection: `tags`
- Fields: `ownerId` (Ascending), `createdAt` (Descending)

---

## 🔌 Firebase Functions (OPTIONAL - Advanced)

### Automated Fraud Detection

Create `functions/index.js`:

```javascript
const functions = require("firebase-functions");
const admin = require("firebase-admin");

admin.initializeApp();
const db = admin.firestore();

// Monitor fraud attempts
exports.onSecurityLog = functions.firestore
  .document("security_logs/{logId}")
  .onCreate(async (snap) => {
    const log = snap.data();
    
    if (log.eventType === "potential_fraud_detected") {
      // Alert admin
      await db.collection("admin_alerts").add({
        type: "fraud",
        tagId: log.tagId,
        timestamp: admin.firestore.Timestamp.now(),
        severity: "high",
        read: false
      });
      
      // Send notification (optional)
      console.log(`🚨 Fraud detected on tag: ${log.tagId}`);
    }
  });

// Clean up old logs (90 days)
exports.cleanupOldLogs = functions.pubsub
  .schedule("every day 02:00")
  .timeZone("Asia/Kolkata")
  .onRun(async () => {
    const ninetyDaysAgo = new Date();
    ninetyDaysAgo.setDate(ninetyDaysAgo.getDate() - 90);
    
    const snapshot = await db.collection("security_logs")
      .where("timestamp", "<", ninetyDaysAgo)
      .get();
    
    const batch = db.batch();
    snapshot.docs.forEach((doc) => {
      batch.delete(doc.ref);
    });
    
    await batch.commit();
    console.log(`✅ Cleaned up ${snapshot.size} old logs`);
  });
```

**Deploy with:**
```bash
cd functions
firebase deploy --only functions
```

---

## 🔑 Authentication Setup

### Enable Authentication Methods

**Go to**: Firebase Console → Authentication → Sign-in Method

**Enable:**
- ✅ Email/Password
- ✅ Google (for admins)
- ✅ Anonymous (for visitors)

---

## 🌐 Hosting Configuration

### firebase.json

Create/Update `firebase.json`:

```json
{
  "hosting": {
    "public": "public",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "headers": [
      {
        "source": "**/*.@(js|css)",
        "headers": [
          {
            "key": "Cache-Control",
            "value": "public, max-age=3600"
          }
        ]
      },
      {
        "source": "**/*.@(html|json|xml|txt)",
        "headers": [
          {
            "key": "Cache-Control",
            "value": "public, max-age=300"
          }
        ]
      },
      {
        "source": "**",
        "headers": [
          {
            "key": "X-Content-Type-Options",
            "value": "nosniff"
          },
          {
            "key": "X-Frame-Options",
            "value": "SAMEORIGIN"
          },
          {
            "key": "X-XSS-Protection",
            "value": "1; mode=block"
          },
          {
            "key": "Strict-Transport-Security",
            "value": "max-age=31536000; includeSubDomains; preload"
          },
          {
            "key": "Referrer-Policy",
            "value": "strict-origin-when-cross-origin"
          },
          {
            "key": "Content-Security-Policy",
            "value": "default-src 'self' https:; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net https://unpkg.com https://www.gstatic.com https://www.googletagmanager.com https://apis.google.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com;"
          }
        ]
      }
    ],
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ],
    "redirects": [
      {
        "source": "/admin",
        "destination": "/admin.html",
        "type": 301
      },
      {
        "source": "/scan",
        "destination": "/scan.html",
        "type": 301
      },
      {
        "source": "/activate",
        "destination": "/activate.html",
        "type": 301
      }
    ]
  }
}
```

---

## 🌍 Environment Variables

### Create `.env` file

```env
# Firebase
FIREBASE_API_KEY=your_api_key_here
FIREBASE_AUTH_DOMAIN=findvault-55a8e.firebaseapp.com
FIREBASE_PROJECT_ID=findvault-55a8e
FIREBASE_STORAGE_BUCKET=findvault-55a8e.appspot.com
FIREBASE_MESSAGING_SENDER_ID=your_sender_id
FIREBASE_APP_ID=your_app_id

# Payment Gateway (Razorpay)
RZP_KEY=your_razorpay_key
RZP_SECRET=your_razorpay_secret

# Email Service
EMAIL_SERVICE=nodemailer
EMAIL_USER=your_email@gmail.com
EMAIL_PASSWORD=your_app_password

# Admin
ADMIN_EMAIL=admin@yourdomain.com
SUPPORT_EMAIL=support@yourdomain.com

# Environment
NODE_ENV=production
```

### Create `.env.local` (for local development)

```env
# Same as above but for local testing
NODE_ENV=development
```

---

## 📊 Analytics Setup (OPTIONAL)

### Enable Google Analytics

**Go to**: Firebase Console → Analytics

**Verify tracking code in `index.html`:**

```html
<!-- Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-YOUR_MEASUREMENT_ID"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'G-YOUR_MEASUREMENT_ID');
</script>
```

---

## 🔔 Email Notifications (OPTIONAL)

### Setup Cloud Functions for Emails

**Install dependencies:**
```bash
cd functions
npm install nodemailer
```

**Create function:**
```javascript
exports.sendNotification = functions.firestore
  .document("notifications/{notificationId}")
  .onCreate(async (snap) => {
    const notification = snap.data();
    
    // Send email using nodemailer
    // Implementation details...
  });
```

---

## 📞 Admin Setup

### Create Admin User

**Via Firebase Console:**

1. Go to Authentication → Users
2. Add new user (your email)
3. Set custom claims to make admin:

```bash
firebase functions:config:set service.account="path/to/serviceAccountKey.json"
```

**Then run:**

```javascript
const admin = require("firebase-admin");
admin.initializeApp();

admin.auth().setCustomUserClaims("USER_UID", { admin: true })
  .then(() => {
    console.log("Admin user created");
  });
```

---

## 🔒 Production Security Checklist

Before going live:

- [ ] Firestore rules deployed
- [ ] Indexes created
- [ ] Firebase functions deployed
- [ ] Custom domain configured
- [ ] SSL certificate active
- [ ] CORS headers set
- [ ] CSP headers configured
- [ ] Backups enabled
- [ ] Monitoring enabled
- [ ] Alert notifications set
- [ ] Admin users created
- [ ] Test payment processing
- [ ] Test email notifications
- [ ] Verify analytics tracking
- [ ] Check error logs
- [ ] Test fraud detection
- [ ] Verify security logging
- [ ] Admin dashboard working
- [ ] Help features active
- [ ] Mobile experience tested

---

## 🚀 Deployment Command

When everything is configured:

```bash
# Deploy Firestore rules
firebase deploy --only firestore:rules

# Deploy all functions
firebase deploy --only functions

# Deploy hosting
firebase deploy --only hosting

# Deploy everything
firebase deploy
```

---

## ✅ Verify Production Setup

**Test URLs:**

```
https://findvault-55a8e.web.app          → Homepage
https://findvault-55a8e.web.app/admin    → Admin Dashboard
https://findvault-55a8e.web.app/scan     → Scan Page
https://findvault-55a8e.web.app/activate → Activation
https://findvault-55a8e.web.app/privacy  → Privacy Policy
https://findvault-55a8e.web.app/terms    → Terms
```

**Test Features:**

1. Activate a test tag
2. Scan from different device
3. Verify fraud blocking ✓
4. Check admin fraud logs ✓
5. Test help features ✓
6. Verify PWA installation ✓

---

## 📞 Support

**Documentation:**
- Firebase Docs: https://firebase.google.com/docs
- Firestore: https://firebase.google.com/docs/firestore
- Security Rules: https://firebase.google.com/docs/firestore/security

**Need Help?**
- Email: support@yourdomain.com
- Docs: See PRODUCTION_DEPLOYMENT.md

---

**Version**: 1.0  
**Status**: ✅ Ready  
**Last Updated**: February 3, 2026
