# Rental Platform - Database & Architecture Plan

## 📁 Project Structure

```
backend/
├── app/
│   ├── __init__.py              # App factory, extensions, CORS, logging, rate limit
│   ├── models/
│   │   ├── __init__.py          # Import all models
│   │   ├── user.py              # User model
│   │   ├── property.py          # Property (house/car) model
│   │   ├── booking.py           # Booking/Reservation model
│   │   ├── review.py            # Review/Rating model
│   │   └── enums.py             # All enums (UserRole, PropertyType, etc.)
│   ├── routes/
│   │   ├── __init__.py          # Register all blueprints
│   │   ├── auth.py              # Authentication routes
│   │   ├── users.py             # User management routes
│   │   ├── properties.py        # Property listing/management routes
│   │   ├── bookings.py          # Booking routes
│   │   └── reviews.py           # Review routes
│   ├── services/
│   │   ├── __init__.py
│   │   ├── auth_service.py      # Authentication logic
│   │   ├── user_service.py      # User business logic
│   │   ├── property_service.py  # Property business logic
│   │   ├── booking_service.py   # Booking business logic
│   │   └── email_service.py     # Email notifications
│   └── utils/
│       ├── __init__.py
│       ├── validators.py        # Input validation helpers
│       └── decorators.py        # Custom decorators (auth_required, etc.)
├── config.py
├── passenger_wsgi.py
├── requirements.txt
├── .env
├── .env.example
└── .gitignore
```

## 🗄️ Database Models

### 1. **User Model** (app/models/user.py)

**Columns:**
- `id` - UUID (primary key)
- `first_name` - String(50), required
- `last_name` - String(50), required
- `username` - String(50), unique, required
- `email` - String(120), unique, required, indexed
- `phone_number` - String(20), unique, nullable
- `is_email_verified` - Boolean, default False
- `password_hash` - String(255), required
- `role` - Enum (UserRole), default 'customer'
- `profile_image` - String(255), nullable
- `date_of_birth` - Date, nullable
- `address` - Text, nullable
- `city` - String(100), nullable
- `country` - String(100), nullable
- `is_active` - Boolean, default True
- `is_verified` - Boolean, default False (for owner verification)
- `created_at` - DateTime, auto
- `updated_at` - DateTime, auto

**Relationships:**
- owned_properties (one-to-many)
- bookings (one-to-many)
- reviews_given (one-to-many)
- reviews_received (one-to-many as property owner)

### 2. **Property Model** (app/models/property.py)

**Columns:**
- `id` - UUID (primary key)
- `owner_id` - UUID, ForeignKey(users.id)
- `title` - String(200), required
- `description` - Text, required
- `property_type` - Enum (PropertyType: HOUSE, APARTMENT, CAR, MOTORCYCLE)
- `category` - String(50) (e.g., SUV, Sedan, Villa, Studio)
- `price_per_day` - Decimal(10,2), required
- `price_per_week` - Decimal(10,2), nullable
- `price_per_month` - Decimal(10,2), nullable
- `currency` - String(3), default 'USD'
- `address` - Text, nullable (for houses)
- `city` - String(100), required
- `country` - String(100), required
- `latitude` - Float, nullable
- `longitude` - Float, nullable
- `bedrooms` - Integer, nullable (for houses)
- `bathrooms` - Integer, nullable (for houses)
- `max_guests` - Integer, nullable (for houses)
- `square_feet` - Integer, nullable (for houses)
- `year` - Integer, nullable (for cars)
- `make` - String(50), nullable (for cars - e.g., Toyota)
- `model` - String(50), nullable (for cars - e.g., Camry)
- `seats` - Integer, nullable (for cars)
- `transmission` - Enum (TransmissionType: MANUAL, AUTOMATIC), nullable
- `fuel_type` - Enum (FuelType: PETROL, DIESEL, ELECTRIC, HYBRID), nullable
- `mileage` - Integer, nullable (for cars)
- `license_plate` - String(20), nullable (for cars)
- `features` - JSON (amenities/features list)
- `images` - JSON (array of image URLs)
- `is_available` - Boolean, default True
- `is_verified` - Boolean, default False
- `status` - Enum (PropertyStatus: ACTIVE, INACTIVE, UNDER_REVIEW)
- `rating_average` - Float, default 0.0
- `review_count` - Integer, default 0
- `created_at` - DateTime, auto
- `updated_at` - DateTime, auto

**Relationships:**
- owner (many-to-one with User)
- bookings (one-to-many)
- reviews (one-to-many)

### 3. **Booking Model** (app/models/booking.py)

**Columns:**
- `id` - UUID (primary key)
- `user_id` - UUID, ForeignKey(users.id)
- `property_id` - UUID, ForeignKey(properties.id)
- `booking_number` - String(20), unique (auto-generated)
- `start_date` - Date, required
- `end_date` - Date, required
- `total_days` - Integer, required
- `price_per_day` - Decimal(10,2), required (snapshot at booking time)
- `total_price` - Decimal(10,2), required
- `status` - Enum (BookingStatus: PENDING, CONFIRMED, CANCELLED, COMPLETED, REJECTED)
- `payment_status` - Enum (PaymentStatus: PENDING, PAID, REFUNDED, FAILED)
- `payment_method` - String(50), nullable
- `payment_id` - String(100), nullable (payment gateway reference)
- `guest_count` - Integer, nullable
- `special_requests` - Text, nullable
- `cancelled_at` - DateTime, nullable
- `cancelled_by` - UUID, nullable (ForeignKey to users)
- `cancellation_reason` - Text, nullable
- `created_at` - DateTime, auto
- `updated_at` - DateTime, auto

**Relationships:**
- user (many-to-one)
- property (many-to-one)
- review (one-to-one)

### 4. **Review Model** (app/models/review.py)

**Columns:**
- `id` - UUID (primary key)
- `booking_id` - UUID, ForeignKey(bookings.id), unique
- `user_id` - UUID, ForeignKey(users.id)
- `property_id` - UUID, ForeignKey(properties.id)
- `rating` - Integer (1-5), required
- `cleanliness_rating` - Integer (1-5), nullable
- `communication_rating` - Integer (1-5), nullable
- `value_rating` - Integer (1-5), nullable
- `location_rating` - Integer (1-5), nullable (for houses)
- `condition_rating` - Integer (1-5), nullable (for cars)
- `comment` - Text, nullable
- `owner_response` - Text, nullable
- `owner_response_at` - DateTime, nullable
- `is_verified` - Boolean, default False (verified purchase)
- `created_at` - DateTime, auto
- `updated_at` - DateTime, auto

**Relationships:**
- booking (one-to-one)
- user (many-to-one)
- property (many-to-one)

### 5. **Enums** (app/models/enums.py)

```python
# User Roles
UserRole: CUSTOMER, OWNER, ADMIN

# Property Types
PropertyType: HOUSE, APARTMENT, CAR, MOTORCYCLE

# Property Status
PropertyStatus: ACTIVE, INACTIVE, UNDER_REVIEW, SUSPENDED

# Booking Status
BookingStatus: PENDING, CONFIRMED, CANCELLED, COMPLETED, REJECTED

# Payment Status
PaymentStatus: PENDING, PAID, REFUNDED, FAILED, PARTIAL

# Transmission Type (for vehicles)
TransmissionType: MANUAL, AUTOMATIC

# Fuel Type (for vehicles)
FuelType: PETROL, DIESEL, ELECTRIC, HYBRID
```

## 🛣️ API Routes Plan

### Authentication Routes (`/api/auth`)
- POST `/register` - User registration
- POST `/login` - User login
- POST `/logout` - User logout
- POST `/verify-email` - Verify email
- POST `/resend-verification` - Resend verification email
- POST `/forgot-password` - Request password reset
- POST `/reset-password` - Reset password

### User Routes (`/api/users`)
- GET `/me` - Get current user profile
- PUT `/me` - Update current user profile
- GET `/:id` - Get user by ID (public profile)
- DELETE `/me` - Delete account
- POST `/me/upload-avatar` - Upload profile image

### Property Routes (`/api/properties`)
- GET `/` - List all properties (with filters)
- POST `/` - Create new property (owner only)
- GET `/:id` - Get property details
- PUT `/:id` - Update property (owner only)
- DELETE `/:id` - Delete property (owner only)
- GET `/my-properties` - Get current user's properties
- POST `/:id/upload-images` - Upload property images

### Booking Routes (`/api/bookings`)
- POST `/` - Create new booking
- GET `/` - Get all bookings (filtered by user role)
- GET `/:id` - Get booking details
- PUT `/:id/confirm` - Confirm booking (owner only)
- PUT `/:id/cancel` - Cancel booking
- PUT `/:id/complete` - Mark booking as completed
- GET `/my-bookings` - Get current user's bookings
- GET `/property/:id/bookings` - Get bookings for a property (owner only)

### Review Routes (`/api/reviews`)
- POST `/` - Create review (after completed booking)
- GET `/property/:id/reviews` - Get all reviews for a property
- GET `/:id` - Get review details
- PUT `/:id` - Update review (own review only)
- DELETE `/:id` - Delete review (own review only)
- POST `/:id/owner-response` - Add owner response

## 🔧 Services Plan

### AuthService
- `register(user_data)` - Handle user registration
- `login(email, password)` - Authenticate user
-   -refresh token
- `verify_email(token)` - Verify email address
- `send_verification_email(user)` - Send verification email
- `request_password_reset(email)` - Initiate password reset
- `reset_password(token, new_password)` - Reset password

### UserService
- `get_user_by_id(user_id)` - Get user profile
- `update_user(user_id, data)` - Update user profile
- `delete_user(user_id)` - Soft delete user
- `upload_avatar(user_id, file)` - Handle avatar upload
- `verify_user(user_id)` - Verify owner account

### PropertyService
- `create_property(owner_id, data)` - Create new property
- `get_properties(filters)` - Get filtered property list
- `get_property_by_id(property_id)` - Get property details
- `update_property(property_id, data)` - Update property
- `delete_property(property_id)` - Delete property
- `check_availability(property_id, start_date, end_date)` - Check availability
- `upload_images(property_id, files)` - Handle image uploads

### BookingService
- `create_booking(user_id, data)` - Create new booking
- `get_bookings(filters)` - Get filtered bookings
- `confirm_booking(booking_id)` - Confirm booking
- `cancel_booking(booking_id, user_id, reason)` - Cancel booking
- `complete_booking(booking_id)` - Mark as completed
- `calculate_price(property_id, start_date, end_date)` - Calculate total price

### EmailService
- `send_welcome_email(user)` - Send welcome email
- `send_verification_email(user, token)` - Send email verification
- `send_booking_confirmation(booking)` - Confirm booking via email
- `send_cancellation_email(booking)` - Notify cancellation
- `send_review_reminder(booking)` - Remind to leave review

## 🔐 Additional Considerations

### Security
- JWT tokens for authentication
- Password hashing (bcrypt)
- Email verification required for bookings
- Owner verification for property listings
- Rate limiting per endpoint
- Input validation and sanitization

### Features for Future
- Image upload (local/S3)
- Payment gateway integration (Stripe/PayPal)
- Availability calendar
- Pricing rules (weekend rates, seasonal pricing)
- Discount codes/coupons
- Wishlist/Favorites
- Messaging between users and owners
- Search with filters (price range, location, dates)
- Notifications system
- Admin dashboard
- Analytics and reports

### Database Indexes
- User: email, username
- Property: city, property_type, is_available, created_at
- Booking: user_id, property_id, status, start_date, end_date
- Review: property_id, user_id