# Database Setup Guide - Textile Manager

This guide will help you set up a fully functional Firebase Firestore database for your Textile Manager application.

## 🚀 Quick Start

### 1. Firebase Project Setup

1. Go to [Firebase Console](https://console.firebase.google.com/)
2. Create a new project or select an existing one
3. Enable Firestore Database in production mode
4. Enable Authentication with Email/Password provider
5. Enable Storage (optional, for receipt uploads)

### 2. Get Firebase Configuration

1. In Firebase Console, go to Project Settings
2. Scroll down to "Your apps" section
3. Click "Add app" and select Web (</>) 
4. Register your app and copy the configuration object

### 3. Environment Configuration

1. Copy `env.example` to `.env.local`
2. Fill in your Firebase configuration values:

```env
NEXT_PUBLIC_FIREBASE_API_KEY=your-api-key-here
NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN=your-project.firebaseapp.com
NEXT_PUBLIC_FIREBASE_PROJECT_ID=your-project-id
NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET=your-project.appspot.com
NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID=123456789
NEXT_PUBLIC_FIREBASE_APP_ID=your-app-id
```

### 4. Deploy Database Rules and Indexes

```bash
# Install Firebase CLI if you haven't already
npm install -g firebase-tools

# Login to Firebase
firebase login

# Initialize Firebase in your project (if not done already)
firebase init

# Deploy Firestore rules and indexes
firebase deploy --only firestore
```

### 5. Run the Application

```bash
npm run dev
```

The application will automatically:
- Detect existing localStorage data
- Migrate it to Firebase on first login
- Set up the database schema

## 📊 Database Schema

### Collections Overview

| Collection | Purpose | Key Features |
|------------|---------|--------------|
| `shops` | Shop profiles and settings | Multi-tenant support |
| `users` | User accounts and roles | Role-based access control |
| `customers` | Customer information | Search and analytics |
| `customerMeasurements` | Customer measurements | Linked to customers |
| `inventory` | Fabric and material inventory | Stock tracking |
| `tailoringItems` | Available services/items | Pricing and categories |
| `employees` | Staff management | Role-based assignments |
| `orders` | Customer orders | Status tracking, workflow |
| `incomeTransactions` | Revenue tracking | Payment methods, categories |
| `expenseTransactions` | Cost tracking | Employee expenses, receipts |
| `appearanceSettings` | UI preferences | Per-shop customization |
| `notificationSettings` | SMS/WhatsApp config | Communication settings |
| `auditLogs` | Change tracking | Security and compliance |
| `reportData` | Cached reports | Performance optimization |

### Key Features

- **Multi-tenant**: Each shop has isolated data
- **Role-based access**: Owner, Manager, Employee roles
- **Audit trail**: All changes are logged
- **Real-time updates**: Live data synchronization
- **Offline support**: Works without internet
- **Data migration**: Automatic localStorage to Firebase migration

## 🔧 Development Setup

### Using Firebase Emulators (Recommended for Development)

1. Install Firebase CLI tools:
```bash
npm install -g firebase-tools
```

2. Start the emulators:
```bash
firebase emulators:start
```

3. The emulators will run on:
   - Firestore: http://localhost:8080
   - Auth: http://localhost:9099
   - Storage: http://localhost:9199
   - Emulator UI: http://localhost:4000

4. Your app will automatically connect to emulators in development mode.

### Database Service Usage

```typescript
import { 
  customerService, 
  orderService, 
  inventoryService 
} from '@/lib/database';

// Create a new customer
const result = await customerService.create({
  name: 'John Doe',
  phone: '+1234567890',
  shopId: 'shop-123'
});

// Get orders by status
const orders = await orderService.getMany([
  { field: 'status', operator: '==', value: 'New' }
], { orderBy: 'orderDate', orderDirection: 'desc' }, shopId);

// Real-time listener
const unsubscribe = customerService.onCollectionChange(
  (customers) => {
    console.log('Customers updated:', customers);
  },
  [], // filters
  shopId
);
```

## 🔒 Security Rules

The database includes comprehensive security rules:

- **Authentication required**: All operations require valid user
- **Shop isolation**: Users can only access their shop's data
- **Role-based permissions**: Different access levels for owners, managers, employees
- **Data validation**: Ensures data integrity
- **Audit protection**: Audit logs are read-only

### User Roles

| Role | Permissions |
|------|-------------|
| **Owner** | Full access to all shop data, can manage users |
| **Manager** | Can manage inventory, employees, settings |
| **Employee** | Can view and create orders, customers, transactions |

## 📈 Performance Optimization

### Indexes

The database includes optimized indexes for:
- Shop-based queries (all collections)
- Date range queries (orders, transactions)
- Status-based filtering (orders, employees)
- Search functionality (customers, inventory)

### Caching

- Report data is cached for performance
- Real-time listeners minimize unnecessary reads
- Pagination support for large datasets

## 🔄 Data Migration

The system automatically migrates existing localStorage data to Firebase:

1. **Detection**: Checks for existing localStorage data on first login
2. **Migration**: Transfers all data to Firebase with proper structure
3. **Cleanup**: Removes localStorage data after successful migration
4. **Validation**: Ensures data integrity during migration

### Manual Migration

```typescript
import { runMigration } from '@/lib/database';

const result = await runMigration(shopId, userId);
console.log('Migration result:', result);
```

## 🛠️ Troubleshooting

### Common Issues

1. **Permission Denied**
   - Check if user is authenticated
   - Verify user has access to the shop
   - Ensure security rules are deployed

2. **Index Errors**
   - Deploy Firestore indexes: `firebase deploy --only firestore:indexes`
   - Wait for indexes to build (can take several minutes)

3. **Migration Issues**
   - Check browser console for detailed error messages
   - Ensure Firebase configuration is correct
   - Verify user has proper permissions

### Debug Mode

Enable debug logging:

```typescript
import { enableNetwork, disableNetwork } from 'firebase/firestore';
import { db } from '@/lib/firebase';

// Enable debug logging
if (process.env.NODE_ENV === 'development') {
  // Firebase debug logging is enabled automatically in development
}
```

## 📚 API Reference

### Service Methods

All services extend the base `DatabaseService` class with these methods:

- `create(data)` - Create new document
- `getById(id)` - Get document by ID
- `update(id, data)` - Update document
- `delete(id)` - Delete document
- `getMany(filters, pagination, shopId)` - Query multiple documents
- `onDocumentChange(id, callback)` - Real-time document listener
- `onCollectionChange(callback, filters, shopId)` - Real-time collection listener

### Extended Services

- `customerServiceExtended` - Customer search and statistics
- `orderServiceExtended` - Order status management and filtering
- `inventoryServiceExtended` - Stock management and low-stock alerts

## 🔮 Future Enhancements

Planned features:
- Full-text search with Algolia integration
- Advanced analytics and reporting
- Multi-location support
- Integration with payment gateways
- Mobile app synchronization
- Backup and restore functionality

## 📞 Support

For issues or questions:
1. Check the troubleshooting section above
2. Review Firebase Console for errors
3. Check browser developer tools console
4. Refer to [Firebase Documentation](https://firebase.google.com/docs/firestore)

---

**Note**: This database setup provides a production-ready, scalable solution for your textile management needs. The schema is designed to handle growth and can be extended as your business requirements evolve.
