Project Flow & Architecture
===========================

This backend application uses Node.js, Express, Sequelize, and PostgreSQL to provide a robust API featuring Authentication, Role-Based Access Control (RBAC), Blog Posts, and Nested Comments.

Database Initialization
---------------------
1. Setup Database: `npm run db:setup` runs `scripts/setupDb.js` to create the PostgreSQL database if it does not exist.
2. Table Synchronization: When the server starts (`npm start` or `npm run dev`), `src/server.js` calls `sequelize.sync({ alter: true })`. This automatically creates and updates the database tables (Users, Roles, Permissions, Posts, Comments, and role_permissions) based on the models defined in `src/models`. Therefore, no external migration tools are needed.

Authentication Flow
-------------------
1. Register: A user sends details to `POST /api/auth/register`. A new `User` is created. Passwords are encrypted using `bcrypt`.
2. Login: `POST /api/auth/login` verifies credentials. A JWT (JSON Web Token) is generated holding user data and an embedded array of permission strings (e.g., `["USERS:READ", "POSTS:CREATE"]`).

Role-Based Access Control (RBAC) Flow
-------------------------------------
1. Roles & Permissions: `Roles` have many `Permissions` (Many-to-Many).
2. Assignment: Using the `RoleController`, an admin can create roles, create permissions, and assign permissions to roles.
3. Middleware: 
   - `authMiddleware`: Verifies the JWT and attaches `req.user`.
   - `authorizeMiddleware(module, action)`: Checks if the embedded permissions in the user's token match the required action (e.g., `POSTS:CREATE`). If it doesn't, a 403 Forbidden is returned.

Posts and Comments Flow
-----------------------
1. Posts: Authenticated users can create posts.
2. Comments: Authenticated users can comment on a post (`parent_id` is null).
3. Nested Replies: Users can reply to comments by providing the `parent_id` of the comment they are replying to.
4. Tree Structure: Fetching a single post (`GET /api/posts/:id`) triggers the `postService.getPostById`. This retrieves the post and all associated comments in a flat array from the database. A helper function then converts this flat array into an infinitely nested tree structure matching the replies and their parents, sending the fully nested structure to the client (like Instagram).
