# MODAVA Backend API

A Node.js TypeScript backend for the MODAVA fashion SaaS platform, built with Express.js and Supabase.

## 🚀 Features

- **Modular Architecture**: Organized by feature modules (auth, vendors, etc.)
- **Supabase Integration**: Authentication, database, and storage
- **Role-based Access Control**: Vendor, admin, staff, and super admin roles
- **RESTful API**: Clean, documented endpoints
- **TypeScript**: Full type safety and IntelliSense
- **Validation**: Request validation with express-validator
- **Error Handling**: Comprehensive error handling middleware
- **Security**: Helmet, CORS, rate limiting

## 📋 Prerequisites

- Node.js 18+ 
- npm or yarn
- Supabase project (for database and auth)

## 🛠️ Setup

### 1. Clone and Install Dependencies

```bash
git clone <repository-url>
cd modava-backend
npm install
```

### 2. Environment Configuration

Copy the environment example file and configure your Supabase credentials:

```bash
cp env.example .env
```

Edit `.env` with your Supabase project details:

```env
# Supabase Configuration
SUPABASE_URL=your_supabase_project_url
SUPABASE_ANON_KEY=your_supabase_anon_key
SUPABASE_SERVICE_ROLE_KEY=your_supabase_service_role_key

# Server Configuration
PORT=3000
NODE_ENV=development
```

### 3. Database Setup

Create the following tables in your Supabase database:

#### Users Table (extends Supabase auth.users)
```sql
-- This is handled by Supabase Auth automatically
-- You can extend it with additional fields if needed
```

#### Vendors Table
```sql
CREATE TABLE vendors (
  id UUID DEFAULT gen_random_uuid() PRIMARY KEY,
  user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,
  email TEXT NOT NULL,
  business_name TEXT,
  profile_picture_url TEXT,
  onboarding_status TEXT DEFAULT 'incomplete' CHECK (onboarding_status IN ('incomplete', 'complete')),
  subscription_plan TEXT DEFAULT 'free',
  created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
  updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);

-- Enable Row Level Security
ALTER TABLE vendors ENABLE ROW LEVEL SECURITY;

-- RLS Policies
CREATE POLICY "Vendors can view own profile" ON vendors
  FOR SELECT USING (auth.uid() = user_id);

CREATE POLICY "Vendors can update own profile" ON vendors
  FOR UPDATE USING (auth.uid() = user_id);

CREATE POLICY "Admins can view all vendors" ON vendors
  FOR ALL USING (
    EXISTS (
      SELECT 1 FROM auth.users 
      WHERE auth.users.id = auth.uid() 
      AND auth.users.raw_user_meta_data->>'role' IN ('admin', 'superadmin')
    )
  );
```

### 4. Development

```bash
# Start development server
npm run dev

# Build for production
npm run build

# Start production server
npm start
```

## 📚 API Documentation

### Authentication Endpoints

#### POST `/api/auth/signup`
Register a new user and create vendor profile.

**Request Body:**
```json
{
  "email": "vendor@example.com",
  "password": "securepassword",
  "business_name": "Fashion Studio" // optional
}
```

**Response:**
```json
{
  "success": true,
  "data": {
    "user": { /* Supabase user object */ },
    "vendor": { /* Vendor profile */ },
    "access_token": "jwt_token",
    "refresh_token": "refresh_token"
  },
  "message": "User registered successfully"
}
```

#### POST `/api/auth/login`
Login existing user.

**Request Body:**
```json
{
  "email": "vendor@example.com",
  "password": "securepassword"
}
```

#### GET `/api/auth/profile`
Get current user profile (requires authentication).

#### POST `/api/auth/logout`
Logout user (requires authentication).

### Vendor Endpoints

#### GET `/api/vendors/me`
Get current vendor profile (requires authentication).

#### POST `/api/vendors/onboarding`
Complete vendor onboarding (requires authentication).

**Request Body:**
```json
{
  "business_name": "Fashion Studio",
  "profile_picture_url": "https://example.com/photo.jpg" // optional
}
```

#### PUT `/api/vendors/profile`
Update vendor profile (requires authentication).

**Request Body:**
```json
{
  "business_name": "Updated Studio Name",
  "profile_picture_url": "https://example.com/new-photo.jpg",
  "subscription_plan": "premium"
}
```

#### GET `/api/vendors/:id`
Get vendor by ID (admin only).

#### GET `/api/vendors`
Get all vendors (admin only).

## 🔐 Authentication

All protected endpoints require a Bearer token in the Authorization header:

```
Authorization: Bearer <supabase_access_token>
```

## 🏗️ Project Structure

```
src/
├── config/
│   └── supabase.ts          # Supabase client configuration
├── middlewares/
│   ├── auth.ts              # Authentication middleware
│   ├── errorHandler.ts      # Error handling middleware
│   └── validation.ts        # Request validation middleware
├── modules/
│   ├── auth/
│   │   ├── controller.ts    # Auth controller
│   │   └── routes.ts        # Auth routes
│   └── vendors/
│       ├── controller.ts    # Vendor controller
│       ├── service.ts       # Vendor service
│       └── routes.ts        # Vendor routes
├── types/
│   └── index.ts             # TypeScript type definitions
└── index.ts                 # Main application entry point
```

## 🚀 Deployment

### Vercel Deployment

1. Install Vercel CLI:
```bash
npm i -g vercel
```

2. Deploy:
```bash
vercel
```

3. Set environment variables in Vercel dashboard.

### Environment Variables

- `SUPABASE_URL`: Your Supabase project URL
- `SUPABASE_ANON_KEY`: Your Supabase anon key
- `SUPABASE_SERVICE_ROLE_KEY`: Your Supabase service role key
- `PORT`: Server port (default: 3000)
- `NODE_ENV`: Environment (development/production)

## 🔧 Development Scripts

- `npm run dev`: Start development server with hot reload
- `npm run build`: Build for production
- `npm start`: Start production server
- `npm run lint`: Run ESLint
- `npm run lint:fix`: Fix ESLint errors

## 📝 Future Modules

The modular structure is ready for additional features:

- `/modules/customers/` - Customer management
- `/modules/orders/` - Order tracking
- `/modules/invoices/` - Invoice generation
- `/modules/subscriptions/` - Subscription management
- `/modules/ai/` - AI assistance features
- `/modules/admin/` - Admin panel functionality

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests if applicable
5. Submit a pull request

## 📄 License

MIT License - see LICENSE file for details. 