# 🚀 Goa-GEL Automatic Initialization Guide

This guide explains the automatic initialization process that runs when you start the Goa-GEL platform for the first time.

---

## 📋 What Happens on First Boot?

When you run `docker-compose up` for the first time, the backend automatically:

### 1. **Database Initialization** 📊
- ✅ Waits for PostgreSQL to be ready
- ✅ Runs all database migrations
- ✅ Seeds initial data (admin user, sample departments, workflows)

### 2. **Blockchain Setup** 🔗
- ✅ Generates a secure platform wallet with mnemonic
- ✅ Funds the wallet from the dev network
- ✅ Deploys all smart contracts:
  - License NFT Contract
  - Approval Manager Contract
  - Department Registry Contract
  - Workflow Registry Contract
- ✅ Updates `.env` file with generated addresses

### 3. **Environment Configuration** 🔐
- ✅ Generates secure keys and addresses
- ✅ Updates `backend/.env` automatically
- ✅ No manual configuration needed!

---

## 🎯 Quick Start

```bash
# 1. Start all services
docker-compose up -d

# 2. Wait 1-2 minutes for initialization
# Watch the logs to see progress
docker-compose logs -f api

# 3. Access the platform
open http://localhost:4200
```

**That's it!** Everything is configured automatically.

---

## 📝 Generated Values

After initialization, check `backend/.env` for:

```bash
# Platform Wallet (Generated)
PLATFORM_WALLET_ADDRESS=0x...
PLATFORM_WALLET_PRIVATE_KEY=0x...
PLATFORM_WALLET_MNEMONIC=word word word...

# Smart Contract Addresses (Deployed)
CONTRACT_ADDRESS_LICENSE_NFT=0x...
CONTRACT_ADDRESS_APPROVAL_MANAGER=0x...
CONTRACT_ADDRESS_DEPARTMENT_REGISTRY=0x...
CONTRACT_ADDRESS_WORKFLOW_REGISTRY=0x...
```

---

## 🔍 Initialization Logs

Watch the initialization process:

```bash
# View API logs
docker-compose logs -f api
```

You'll see:
```
🚀 Starting Goa-GEL Backend Initialization...
📊 Step 1: Database initialization...
✅ PostgreSQL is up
📦 First time setup - running migrations...
🌱 Seeding initial data...
✅ Database initialized successfully!
🔗 Step 2: Blockchain initialization...
🔐 Generating platform wallet...
📝 Platform Wallet Address: 0x...
💰 Funding platform wallet...
📜 Deploying smart contracts...
✅ Blockchain initialization complete!
🎯 Step 3: Starting NestJS application...
```

---

## 🗃️ Seeded Data

The database is automatically seeded with:

### Admin User
- **Email**: `admin@goa.gov.in`
- **Password**: `Admin@123` (Change after first login!)
- **Role**: ADMIN

### Sample Departments
1. **Tourism Department** (TOURISM)
2. **Trade Department** (TRADE)
3. **Health Department** (HEALTH)

### Sample Workflows
- Resort License Workflow (Tourism + Health)
- Trade License Workflow (Trade + Health)

---

## 🔄 Re-initialization

If you need to re-initialize:

```bash
# Stop and remove everything
docker-compose down -v

# Start fresh (will auto-initialize)
docker-compose up -d
```

**Warning**: This deletes all data!

---

## 🔐 Security Notes

### Development Environment
- Uses pre-funded dev account for deployment
- Generates random mnemonics
- All values are visible in logs (for debugging)

### Production Environment
**Before deploying to production:**

1. ✅ Change admin password immediately
2. ✅ Backup the mnemonic phrase securely
3. ✅ Store private keys in secret management (Vault, AWS Secrets)
4. ✅ Disable debug logging
5. ✅ Use proper firewall rules
6. ✅ Enable SSL/TLS
7. ✅ Rotate API keys regularly

---

## 📊 Verification

### Check Database
```bash
docker exec -it goa-gel-postgres psql -U postgres -d goa_gel_platform -c "\dt"
```

### Check Blockchain
```bash
# Get block number
curl -X POST -H "Content-Type: application/json" \
  --data '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}' \
  http://localhost:8545

# View in Blockscout
open http://localhost:4000
```

### Check Contracts
```bash
# View deployed contracts in .env
cat backend/.env | grep CONTRACT_ADDRESS
```

---

## 🛠️ Manual Initialization (if needed)

If automatic initialization fails:

```bash
# 1. Enter the API container
docker exec -it goa-gel-api sh

# 2. Run migrations manually
npm run migrate:latest

# 3. Run seeds
npm run seed:run

# 4. Deploy contracts
node scripts/init-blockchain.js

# 5. Restart the API
docker-compose restart api
```

---

## 📞 Troubleshooting

### "Database initialization failed"
- **Check**: PostgreSQL is running
- **Solution**: `docker-compose restart postgres`

### "Blockchain not available"
- **Check**: Besu node is running and mining
- **Solution**: `docker-compose restart besu-node-1`
- **Verify**: `curl http://localhost:8545`

### "Contract deployment failed"
- **Check**: Besu node logs
- **Solution**: Ensure node is mining blocks
- **Retry**: `docker-compose restart api`

### ".env file not updated"
- **Check**: File permissions
- **Solution**: Ensure `backend/.env` is writable
- **Manual**: Copy values from logs to `.env`

---

## 🎯 What Gets Persisted?

### Persistent Data (Survives restart)
✅ Database data (in `postgres_data` volume)
✅ Blockchain data (in `besu_data` volume)
✅ MinIO files (in `minio_data` volume)
✅ `.env` file (in `backend/.env`)
✅ Initialization flag (in `api_data` volume)

### Ephemeral Data (Lost on `docker-compose down -v`)
❌ All of the above (with `-v` flag)

---

## 📚 Related Documentation

- **User Guide**: `/viewer.html?doc=USER_GUIDE`
- **Testing Guide**: `/viewer.html?doc=E2E_TESTING_GUIDE`
- **Architecture**: `ARCHITECTURE_GUIDE.md`
- **Deployment**: `DOCKER_SETUP.md`

---

## ✅ Checklist

After successful initialization, you should have:

- [x] All 9 services running
- [x] Database migrated and seeded
- [x] Smart contracts deployed
- [x] Platform wallet generated
- [x] `.env` file populated
- [x] Admin user created
- [x] Sample departments created
- [x] Frontend accessible at http://localhost:4200

**Status**: Ready for development! 🎉

---

**Version**: 1.0.0
**Last Updated**: February 2026
**Auto-Initialization**: Enabled ✅
