# AI & Developer Workstation Guide

**Variable Remuneration, Compensation, and Commissions System - Hoteles Estelar**

---

This document outlines the environment configurations (Development vs. Production), API keys, and recommended AI integration tools (like Model Context Protocol servers) designed to optimize this workspace for AI agents (such as Antigravity-cli / agy) and human developers alike.

---

## 1. Environment Configurations (.env Blueprints)

The Next.js application separates environment secrets between local active development and production servers.

### 1.1. Development Environment (`.env.development`)
This file lives in the root directory during development. It configures connection strings to local/sandbox instances.

```bash
# -----------------------------------------------------------------------------
# Database Setup
# -----------------------------------------------------------------------------
# Connection string pointing to your local development PostgreSQL instance.
# Prisma uses this URL to run migrations and execute DB queries.
DATABASE_URL="postgresql://postgres:postgres@localhost:5432/special_hotel_dev?schema=public"

# -----------------------------------------------------------------------------
# Next.js Application Settings
# -----------------------------------------------------------------------------
# The host address of your local Next.js client (default dev port is 3000)
NEXT_PUBLIC_APP_URL="http://localhost:3000"

# Secret token used by NextAuth / custom session helper to sign JWTs.
# Generate a secure key locally using: openssl rand -base64 32
NEXTAUTH_SECRET="dev_secret_jwt_sign_key_change_me_locally"

# -----------------------------------------------------------------------------
# n8n Workflow Engine Integration
# -----------------------------------------------------------------------------
# Webhook URL pointing to your local n8n instance where calculations and 
# AI workflows are executed.
N8N_WEBHOOK_URL="http://localhost:5678/webhook/calculate-commissions"

# Local authorization secret shared between Next.js and n8n.
# Incoming webhooks from n8n calling the Next.js API must provide this token 
# in the 'x-n8n-signature' header.
N8N_WEBHOOK_SECRET="local_shared_signature_to_verify_n8n_callbacks"
```

---

### 1.2. Production Environment (`.env.production`)
Production values are configured inside the live environment (e.g. injected into the container via Dockge).

```bash
# -----------------------------------------------------------------------------
# Database Setup
# -----------------------------------------------------------------------------
# Secure production database URL. Must be reachable only within the isolated 
# network environment (e.g. via private container network aliases).
DATABASE_URL="postgresql://postgres:secure_db_prod_pass@postgres-vpn:5432/special_hotel?schema=public"

# -----------------------------------------------------------------------------
# Next.js Application Settings
# -----------------------------------------------------------------------------
# The public or VPN-locked domain resolved by Caddy
NEXT_PUBLIC_APP_URL="https://special-hotel.yourdomain.com"

# High-entropy random secret key for production JWT signatures.
NEXTAUTH_SECRET="prod_high_entropy_session_secret_key"

# -----------------------------------------------------------------------------
# n8n Workflow Engine Integration
# -----------------------------------------------------------------------------
# Production n8n calculation webhook endpoint (internally routed)
N8N_WEBHOOK_URL="http://n8n:5678/webhook/calculate-commissions"

# Optional application-level security secret.
# NOTE: In production, since Next.js and n8n share a private Docker container 
# network, Caddy blocks all public access to /api/n8n/* endpoints. 
# Because of this network-level isolation, token-based verification is optional 
# but recommended as a defense-in-depth practice.
N8N_WEBHOOK_SECRET="prod_shared_signature_to_verify_n8n_callbacks"
```

---

## 2. Optimizing the Workspace for the Antigravity Agent (agy)

To make this codebase highly friendly for the **Antigravity agent (`agy`)**, you can configure the following Model Context Protocol (MCP) servers. Once registered in the agent's active configuration, `agy` is equipped with specialized tools to inspect database schemas, execute and debug n8n workflows, manage git versions, and run automated browser checks.

### 2.1. Recommended MCP Servers for agy

#### A. n8n MCP Server (Official Beta / Community)
Exposes tools to read, execute, and write workflows directly on the n8n canvas.
* **Use Case**: Allows `agy` to trigger calculation runs, inspect failing nodes on the canvas, check webhook logs, and modify workflows dynamically.
* **Harness Registration**:
  ```json
  "n8n": {
    "command": "npx",
    "args": ["-y", "n8n-mcp"],
    "env": {
      "N8N_API_KEY": "your_n8n_api_key_here",
      "N8N_URL": "http://localhost:5678"
    }
  }
  ```

#### B. Prisma Postgres MCP Server (`@prisma/mcp`)
Exposes tools allowing `agy` to interact with the database using type-safe schemas.
* **Use Case**: Allows `agy` to run schema checks, dry-run validations, and automatically inspect database tables during development.
* **Available Tools**: `ListDatabases`, `ExecuteSqlQuery`, `IntrospectSchema`, and `ExecuteRawSql`.
* **Harness Registration**:
  ```json
  "prisma-postgres": {
    "command": "npx",
    "args": ["-y", "@prisma/mcp"],
    "env": {
      "DATABASE_URL": "postgresql://postgres:postgres@localhost:5432/special_hotel_dev?schema=public"
    }
  }
  ```

#### C. PostgreSQL MCP Server (`@modelcontextprotocol/server-postgres`)
Provides raw PostgreSQL connection and querying tools.
* **Use Case**: Enables `agy` to query migration status, seed verification, and raw audit log verification directly.
* **Harness Registration**:
  ```json
  "postgres": {
    "command": "npx",
    "args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://postgres:postgres@localhost:5432/special_hotel_dev"]
  }
  ```

#### D. Git MCP Server (`@modelcontextprotocol/server-git`)
Provides local Git operations tools (clone, commit, diff, log, status).
* **Use Case**: Allows `agy` to review local branches, examine diffs of modified code files, and make structured, micro-commits during development.
* **Harness Registration**:
  ```json
  "git": {
    "command": "npx",
    "args": ["-y", "@modelcontextprotocol/server-git", "/home/gabogg/Proyects/semillero-special-hotel"]
  }
  ```

#### E. Puppeteer MCP Server (`@modelcontextprotocol/server-puppeteer`)
Exposes browser automation tools (take screenshots, click, type, fill forms).
* **Use Case**: Allows `agy` to start a headless browser, render our Next.js pages, and verify layout responsiveness and style details against the style guide without manual developer steps.
* **Harness Registration**:
  ```json
  "puppeteer": {
    "command": "npx",
    "args": ["-y", "@modelcontextprotocol/server-puppeteer"]
  }
  ```

#### F. Forgejo / Gitea MCP Server (`forgejo-mcp` / `gitea-mcp`)
Exposes tools allowing `agy` to interact directly with your Forgejo repository (creating and merging pull requests, reviewing code, creating issues) via API.
* **Use Case**: Enables `agy` to manage issues, automate code review tasks, verify pull request status, and merge pull requests directly using standard API endpoints.
* **Harness Registration**:
  ```json
  "forgejo-mcp": {
    "command": "npx",
    "args": ["-y", "forgejo-mcp"],
    "env": {
      "FORGEJO_REMOTE_URL": "https://git.yourdomain.com",
      "FORGEJO_AUTH_TOKEN": "your_forgejo_api_token_here"
    }
  }
  ```

---

## 3. Managing Pull Requests via CLI (Forgejo Client)

To manage repositories, issues, and pull requests directly from your terminal (similar to GitHub CLI `gh`), you can use **`tea`**, the official Gitea CLI client. Since Forgejo is a fork of Gitea and shares the exact same REST API, `tea` is fully compatible out-of-the-box.

### 3.1. Installing tea on your workstation
For Linux systems, you can download the latest precompiled binary:
```bash
# Download and install the precompiled binary
curl -L -sS https://gitea.com/gitea/tea/releases/download/v0.9.2/tea-0.9.2-linux-amd64 -o /tmp/tea
sudo mv /tmp/tea /usr/local/bin/tea
sudo chmod +x /usr/local/bin/tea
```

### 3.2. Authenticating tea with your Forgejo instance
Configure a login profile for your server:
```bash
tea login add \
  --name forgejo \
  --url https://git.yourdomain.com \
  --token <YOUR_FORGEJO_PERSONAL_ACCESS_TOKEN>
```
*Note: You can generate a Personal Access Token in the Forgejo Web UI under Settings ➔ Applications.*

### 3.3. Standard PR commands
With `tea` configured, you can manage pull requests directly from the repository root:
* **List open PRs**: `tea pulls ls`
* **Checkout a PR locally**: `tea pulls checkout <PR_NUMBER>`
* **Create a new PR**: `tea pulls create --title "My PR" --base main --head my-feature`
* **Merge a PR**: `tea pulls merge <PR_NUMBER>`
* **Approve/Review a PR**: `tea pulls review <PR_NUMBER> --approve`

---

## 4. Testing Procedures & Webhook Testing Flow

Testing must occur in complete isolation from production data. We achieve this by splitting execution paths using dedicated test hooks in both Next.js and n8n.

### 4.1. Development & Test Variables Configuration
During test executions (such as running Jest, Cypress, or integration suites), the application uses the following development-exclusive variables:
* `TEST_DATABASE_URL`: Dedicated database connection URL for test schemas (e.g. `postgresql://.../special_hotel_test`). Migrations are run here independently.
* `N8N_TEST_WEBHOOK_URL`: The specific path n8n exposes for test triggers.

### 4.2. n8n Testing Webhook Routing
All calculations triggered by test suites route to n8n via `/webhook-test` path segments:
1. **Trigger**: Test suite invokes n8n via `POST ${process.env.N8N_TEST_WEBHOOK_URL}/calculate-commissions`.
2. **n8n Path Branching**: 
   - Within the n8n canvas, an **`IF` node** checks: `{{ $json.headers["x-nginx-original-uri"] || $json.path }}` contains `webhook-test`.
   - **True**: The n8n workspace connects to the database utilizing `TEST_DATABASE_URL` credentials. It pulls test sales/goals data and pushes calculations back to the Next.js dev API.
   - **False**: Connects to the main `DATABASE_URL` for production processing.

### 4.3. Running Integration Tests Locally
To run the full sandbox locally:
1. Spin up both databases: `docker compose up -d postgres-dev postgres-test`.
2. Run database migrations on the test database:
   ```bash
   DATABASE_URL=$TEST_DATABASE_URL npx prisma migrate deploy
   ```
3. Run the Next.js development server (which connects to the dev database by default, but switches API routing to test endpoints under integration scripts).
4. Run testing script: `npm run test:integration`.



