# Fix 401 Unauthorized Error - API Authentication

## Problème identifié

L'erreur `401 (Unauthorized)` lors de l'appel à `GET https://api.rollerlogic.com/admin/stats` était due à une **mauvaise configuration CORS** et une **mauvaise détection d'URL d'API** au niveau du frontend.

### Cause racine

1. **CORS manquant**: Le panel admin est servi depuis `https://admin.rollerlogic.com`, mais le serveur API n'autorisait que `https://sysop.rollerlogic.com` comme origin.

2. **Détection d'URL d'API**: Le fichier `admin/js/config.js` utilisait une URL API hardcodée (`http://localhost:3000`) qui ne s'adaptait pas à l'environnement de production (`https://api.rollerlogic.com`).

## Solutions appliquées

### 1. Configuration CORS - Backend (`rollerlogic-api/src/server.ts`)

✅ **Ajout de `https://admin.rollerlogic.com` comme origin autorisé en production**

```typescript
await app.register(cors, {
  origin:
    config.appEnv === "production"
      ? [
          "https://rollerlogic.com",
          "https://www.rollerlogic.com",
          "https://api.rollerlogic.com",
          "https://admin.rollerlogic.com",  // ✅ AJOUTÉ
          "https://sysop.rollerlogic.com",
          "https://localhost",
          "capacitor://localhost",
          "http://localhost",
        ]
      : [...]
});
```

### 2. Détection d'URL d'API - Frontend (`admin/js/config.js`)

✅ **Implémentation d'une détection automatique basée sur le domaine**

```javascript
const getApiUrl = () => {
  const host = window.location.hostname;
  const protocol = window.location.protocol;

  // En production sur admin.rollerlogic.com - utiliser api.rollerlogic.com
  if (host.includes("admin.rollerlogic.com")) {
    return "https://api.rollerlogic.com";
  }

  // En développement local
  if (host.includes("localhost") || host.includes("127.0.0.1")) {
    return `${protocol}//localhost:3000`;
  }

  // Par défaut, utiliser le même host
  return `${protocol}//${host}`;
};
```

### 3. Validation JWT Secret - Backend (`rollerlogic-api/src/config.ts`)

✅ **Ajout d'une validation pour s'assurer que le JWT_SECRET est toujours défini**

```typescript
const jwtSecret = resolveSecret("JWT_SECRET", "JWT_SECRET_FILE");
if (!jwtSecret) {
  throw new Error("Missing env var: JWT_SECRET or JWT_SECRET_FILE");
}
```

## Architecture de déploiement

```
┌─────────────────────────────────────────────────────────────┐
│ Production (HTTPS)                                          │
├──────────────────┬───────────────────┬──────────────────────┤
│ admin.rollerlogic │ api.rollerlogic.com│ rollerlogic.com    │
│ .com             │                    │ (frontend)         │
├──────────────────┴───────────────────┴──────────────────────┤
│ Panel Admin      │ API Server         │ App Mobile/Web     │
│ (HTML + JS)      │ (Node.js/Fastify)  │                    │
│                  │ ✅ CORS OK         │ ✅ CORS OK         │
└──────────────────┴───────────────────┴──────────────────────┘

Flux d'authentification:
1. Admin login sur admin.rollerlogic.com
2. POST /auth/login vers api.rollerlogic.com (CORS OK)
3. Reçoit token JWT + cookie refresh
4. GET /admin/stats avec Authorization Bearer token (CORS OK)
```

## Variables d'environnement requises

```env
# Backend
JWT_SECRET=<secret-key>  # ou JWT_SECRET_FILE=/path/to/secret
APP_ENV=production

# Frontend (auto-détecté basé sur window.location.hostname)
# Aucune variable d'environnement requise
```

## Tests recommandés

```bash
# 1. Test CORS preflight
curl -i -X OPTIONS https://api.rollerlogic.com/admin/stats \
  -H "Origin: https://admin.rollerlogic.com" \
  -H "Access-Control-Request-Method: GET"

# 2. Test login
curl -X POST https://api.rollerlogic.com/auth/login \
  -H "Content-Type: application/json" \
  -H "Origin: https://admin.rollerlogic.com" \
  -d '{"email":"admin@example.com","password":"password"}'

# 3. Test stats avec token
curl -i https://api.rollerlogic.com/admin/stats \
  -H "Authorization: Bearer <token>" \
  -H "Origin: https://admin.rollerlogic.com"
```

## Fichiers modifiés

1. `rollerlogic-api/src/server.ts` - CORS configuration
2. `admin/js/config.js` - API URL auto-detection
3. `rollerlogic-api/src/config.ts` - JWT secret validation
