# Royal Enfield Workflow - Quick Start Guide

## 🚀 **One-Command Setup (New!)**

Everything is now automated! Just run:

```bash
cd Re_Backend
npm run dev
```

That's it! The setup script will automatically:
- ✅ Check if PostgreSQL database exists
- ✅ Create database if missing
- ✅ Install required extensions (`uuid-ossp`)
- ✅ Run all migrations (18 total: create tables, enums, indexes)
- ✅ Auto-seed 30 admin configurations
- ✅ Start the development server

---

## 📋 **Prerequisites**

Before running `npm run dev`, ensure:

1. **PostgreSQL is installed and running**
   ```bash
   # Windows
   # PostgreSQL should be running as a service
   
   # Verify it's running
   psql -U postgres -c "SELECT version();"
   ```

2. **Dependencies are installed**
   ```bash
   npm install
   ```

3. **Environment variables are configured**
   - Copy `.env.example` to `.env`
   - Update database credentials:
     ```env
     DB_HOST=localhost
     DB_PORT=5432
     DB_USER=postgres
     DB_PASSWORD=your_password
     DB_NAME=royal_enfield_workflow
     ```

---

## 🎯 **First Time Setup**

### Step 1: Install & Configure
```bash
cd Re_Backend
npm install
cp .env.example .env
# Edit .env with your database credentials
```

### Step 2: Run Development Server
```bash
npm run dev
```

**Output:**
```
========================================
🚀 Royal Enfield Workflow - Auto Setup
========================================

🔍 Checking if database exists...
📦 Database 'royal_enfield_workflow' not found. Creating...
✅ Database 'royal_enfield_workflow' created successfully!
📦 Installing uuid-ossp extension...
✅ Extension installed!
🔌 Testing database connection...
✅ Database connection established!
🔄 Running migrations...

📋 Creating users table with RBAC and extended SSO fields...
✅ 2025103000-create-users
✅ 2025103001-create-workflow-requests
✅ 2025103002-create-approval-levels
... (18 migrations total)

✅ Migrations completed successfully!

========================================
✅ Setup completed successfully!
========================================

📝 Note: Admin configurations will be auto-seeded on server start.

💡 Next steps:
   1. Server will start automatically
   2. Log in via SSO
   3. Run this SQL to make yourself admin:
      UPDATE users SET role = 'ADMIN' WHERE email = 'your-email@{{APP_DOMAIN}}';

[Config Seed] ✅ Default configurations seeded successfully (30 settings)
info: ✅ Server started successfully on port 5000
```

### Step 3: Make Yourself Admin
After logging in via SSO:

```bash
psql -d royal_enfield_workflow

UPDATE users 
SET role = 'ADMIN'
WHERE email = 'your-email@{{APP_DOMAIN}}';

\q
```

---

## 🔄 **Subsequent Runs**

After initial setup, `npm run dev` will:
- ✅ Skip database creation (already exists)
- ✅ Run any pending migrations (if you pulled new code)
- ✅ Skip config seeding (already has data)
- ✅ Start server immediately

**Typical Output:**
```
========================================
🚀 Royal Enfield Workflow - Auto Setup
========================================

🔍 Checking if database exists...
✅ Database 'royal_enfield_workflow' already exists.
🔌 Testing database connection...
✅ Database connection established!
🔄 Running migrations...
ℹ️  No pending migrations
✅ Migrations completed successfully!

========================================
✅ Setup completed successfully!
========================================

info: ✅ Server started successfully on port 5000
```

---

## 🛠️ **Manual Commands (If Needed)**

### Run Setup Only (Without Starting Server)
```bash
npm run setup
```

### Start Server Without Setup
```bash
npm run dev:no-setup
```

### Run Migrations Only
```bash
npm run migrate
```

### Seed Admin Configs Manually
```bash
npm run seed:config
```

---

## 🔥 **Fresh Database Reset**

If you want to completely reset and start fresh:

```bash
# Drop database
psql -U postgres -c "DROP DATABASE IF EXISTS royal_enfield_workflow;"

# Then just run dev (it will recreate everything)
npm run dev
```

---

## 📊 **Database Structure**

After setup, you'll have:
- **18 migrations** run successfully
- **30 admin configurations** seeded
- **12+ tables** created:
  - `users` (with RBAC roles)
  - `workflow_requests`
  - `approval_levels`
  - `participants`
  - `documents`
  - `work_notes`
  - `tat_alerts`
  - `admin_configurations`
  - `holidays`
  - `notifications`
  - `conclusion_remarks`
  - And more...

---

## 🎉 **That's It!**

Now you can:
- Access API at: `http://localhost:5000`
- View health check: `http://localhost:5000/health`
- Access API docs: `http://localhost:5000/api/v1`

---

## ❓ **Troubleshooting**

### Database Connection Failed
```
Error: Unable to connect to database
```
**Fix:**
- Ensure PostgreSQL is running
- Check credentials in `.env`
- Verify database user has `CREATEDB` permission

### Setup Script Permission Error
```
Error: permission denied to create database
```
**Fix:**
```sql
-- Grant CREATEDB permission to your user
ALTER USER postgres CREATEDB;
```

### Port Already in Use
```
Error: Port 5000 is already in use
```
**Fix:**
- Change `PORT` in `.env`
- Or kill process using port 5000

---

## 🚀 **Production Deployment**

For production:
1. Set `NODE_ENV=production` in `.env`
2. Use `npm run build` to compile TypeScript
3. Use `npm start` (no auto-setup in production)
4. Run migrations separately: `npm run migrate`

---

**Happy Coding!** 🎉

