# Rental Management System Backend

A professional, scalable Node.js/Express backend for managing rentals, inventory, and customers.

## Features
- **Multi-Item Rentals**: Rent multiple items in a single transaction.
- **Accurate Billing**: Snapshotted rates at rent time with automatic cost calculation.
- **Atomic Operations**: ACID transactions for starting and returning rentals.
- **JWT Security**: Role-based access control (ADMIN/STAFF).
- **Normalized DB**: 3NF MySQL schema with indexes for performance.

## Tech Stack
- Node.js & Express.js
- MySQL (mysql2/promise)
- JWT & bcryptjs
- dotenv & morgan

## Prerequisites
- Node.js (LTS)
- MySQL Server

## Setup Instructions

1. **Install Dependencies**
   ```bash
   cd backend
   npm install
   ```

2. **Database Setup**
   - Create a database named `rental_system`.
   - Run the SQL queries in `database/schema.sql`.

3. **Configuration**
   - Update `.env` with your database credentials.

4. **Seed Data**
   ```bash
   node seed.js
   ```

5. **Start Server**
   ```bash
   npm run dev
   ```

## API Reference

### Auth
- `POST /api/auth/login` - Login to get JWT.
- `POST /api/auth/register` - (Admin only) Register new staff.

### Rentals
- `POST /api/rentals/start` - Input: `customer_id`, `items: [{item_id, quantity}]`.
- `POST /api/rentals/return/:id` - Completes rental, calculates cost, and updates item status.

### Items & Customers
- Standard CRUD endpoints at `/api/items` and `/api/customers`.

## Database Design Explanation
- **customers**: Stores end-renter information (separate from system users).
- **items**: Unique `item_code` and `status` tracking.
- **rentals**: Header table for the transaction.
- **rental_items**: Snapshots price and rate type to prevent historical data shifts if prices change.
- **payments**: Tracks payments linked to rentals.

## Rental Logic
On return, the system:
1. Calculates `duration_minutes`.
2. Rounds UP to the nearest hour or day based on `rate_type`.
3. Multiplies by the snapshotted rate.
4. Updates items back to `AVAILABLE` automatically.
