# SmartSolTech Website - AI Coding Agent Instructions

## Project Overview
SmartSolTech is a **Korean tech services company** PWA with an admin panel, portfolio management, Telegram integration, and service calculator. Built with Node.js/Express backend, EJS templating, MongoDB, and modern PWA features.

## Architecture & Key Patterns

### 🏗️ Backend Architecture
- **Main server**: `server.js` - Express app with comprehensive middleware stack
- **Models**: MongoDB with Mongoose ODM - all in `/models/` (User, Portfolio, Service, Contact, SiteSettings)
- **Routes**: RESTful API patterns in `/routes/` - separate files per domain
- **Authentication**: Dual auth system - JWT tokens for API, sessions for web pages
- **Validation**: express-validator middleware in `/middleware/validation.js` with Korean error messages

### 🔑 Authentication Pattern
```javascript
// Two authentication strategies:
// 1. JWT for API endpoints (authenticateToken)
// 2. Session-based for web pages (authenticateSession) 
// See middleware/auth.js for implementations
```

### 📊 Data Models Key Features
- **Portfolio**: Has virtual `primaryImage` getter, text search indexes, and SEO fields
- **Service**: Complex pricing structure with features array (included/not included)
- **User**: bcrypt password hashing with pre-save hook and comparePassword method
- **All models**: Use timestamps and have soft-delete patterns where applicable

### 🛣️ Route Organization
- **Admin routes** (`/admin`): Session-based auth, server-side rendered EJS views
- **API routes** (`/api/*`): JWT auth, JSON responses, rate-limited
- **Public routes** (`/`): Mixed auth (optional), EJS templates with PWA support

## Development Workflow

### 🚀 Essential Commands
```bash
# Development with hot reload and file watching
npm run dev

# Initialize database with admin user and sample data
npm run init-db

# Production build with webpack optimization
npm run build

# Database setup creates:
# - Admin user (from .env: ADMIN_EMAIL/ADMIN_PASSWORD)
# - Sample services, portfolio items, site settings
```

### 🔧 Environment Setup
**Critical `.env` variables**:
- `MONGODB_URI` - Database connection
- `SESSION_SECRET`, `JWT_SECRET` - Security keys
- `ADMIN_EMAIL`, `ADMIN_PASSWORD` - Initial admin account
- `TELEGRAM_BOT_TOKEN` - Optional Telegram integration
- `NODE_ENV` - Controls error verbosity and security settings

## Frontend Architecture

### 🎨 View Layer (EJS Templates)
- **Layout system**: `views/layout.ejs` is main wrapper
- **Partials**: `views/partials/` for reusable components (navigation, footer)
- **Admin panel**: Separate layout `admin/layout.ejs` with different styling
- **Internationalization**: Content in Korean, supports locales in `/locales/`

### 📱 PWA Implementation
- **Service Worker**: `public/sw.js` - caches static files, dynamic routes, and API responses
- **Manifest**: `public/manifest.json` - app metadata and icons
- **Offline-first**: Service worker handles network failures gracefully
- **Cache strategy**: Static files cached immediately, dynamic content cached on demand

### 🎯 Frontend JavaScript Patterns
- **Main script**: `public/js/main.js` - handles navigation, scroll effects, form interactions
- **Calculator**: `public/js/calculator.js` - complex service pricing calculations
- **Libraries**: AOS animations, Tailwind CSS, Socket.io for real-time features

## Key Integration Points

### 📧 Communication Systems
- **Telegram Bot**: Optional integration for admin notifications (contact forms, orders)
- **Email**: Nodemailer for SMTP email sending (contact forms, notifications)
- **Real-time**: Socket.io setup for live updates (dashboard, notifications)

### 🔒 Security Patterns
- **Helmet**: CSP headers allowing specific domains (fonts.googleapis.com, cdnjs.cloudflare.com)
- **Rate limiting**: Applied to `/api/*` routes (100 requests/15min per IP)
- **Input validation**: Korean-language error messages, comprehensive field validation
- **File uploads**: Multer with Sharp image processing, stored in `public/uploads/`

### 🗄️ Database Patterns
- **Connection**: Single MongoDB connection with connection pooling
- **Indexing**: Text search on Portfolio, compound indexes for performance
- **Session storage**: MongoDB session store for persistence

## Business Logic Specifics

### 💰 Service Calculator
- **Complex pricing**: Base price + features + timeline modifiers
- **Multi-step form**: Service selection → customization → contact info → quote
- **Integration**: Calculator data feeds into Contact model for lead tracking

### 🎨 Portfolio Management
- **Image handling**: Multiple images per project, primary image logic
- **Categories**: Predefined categories (web-development, mobile-app, ui-ux-design, etc.)
- **SEO optimization**: Meta fields, structured data for portfolio items

### 👑 Admin Panel Features
- **Dashboard**: Statistics, recent activity, quick actions
- **Content management**: CRUD for Portfolio, Services, Site Settings
- **Media gallery**: File upload with image optimization
- **Contact management**: Lead tracking, status updates, response handling

## Common Tasks & Patterns

### 🔧 Adding New Features
1. **Model**: Create in `/models/` with proper validation and indexes
2. **Routes**: Add to `/routes/` with appropriate auth middleware
3. **Views**: EJS templates in `/views/` using layout system
4. **API**: JSON endpoints with validation middleware
5. **Frontend**: Add to `public/js/` with proper event handling

### 🐛 Debugging Workflow
- **Development**: Use `npm run dev` for auto-restart and detailed logging
- **Database**: Check MongoDB connection and sample data with `npm run init-db`
- **Authentication**: Test both JWT (API) and session (web) auth flows
- **PWA**: Check service worker registration and cache behavior in dev tools

### 📦 Deployment Considerations
- **Environment**: Production requires secure cookies, CSP, and rate limiting
- **Database**: Ensure MongoDB indexes are created for performance
- **Assets**: Static files served by Express, consider CDN for production
- **Monitoring**: Error handling sends different messages based on NODE_ENV

## File Structure Quick Reference
```
├── models/          # MongoDB schemas with business logic
├── routes/          # Express routes (API + web pages)
├── middleware/      # Auth, validation, error handling
├── views/           # EJS templates with Korean content
├── public/          # Static assets + PWA files
├── scripts/         # Database init, dev server, build tools
└── server.js        # Main Express application
```

## Korean Language Notes
- **UI Text**: All user-facing content in Korean
- **Error Messages**: Validation errors in Korean (`middleware/validation.js`)
- **Admin Interface**: Korean labels and messages throughout admin panel
- **SEO Content**: Korean meta descriptions and structured data