# API Endpoints

## Base URL

```
http://localhost:3000/api
```

## Authentication

Todos los endpoints (excepto `/health`) requieren autenticación JWT:

```
Authorization: Bearer <token>
```

---

## Projects

### GET /projects

Lista todos los proyectos.

**Response**:
```json
{
  "projects": [
    {
      "id": "uuid",
      "name": "My Project",
      "description": "Project description",
      "giteaRepoUrl": "http://gitea/owner/repo",
      "k8sNamespace": "my-project",
      "status": "active",
      "createdAt": "2026-01-19T10:00:00Z"
    }
  ]
}
```

### GET /projects/:id

Obtiene detalles de un proyecto.

### POST /projects

Crea un nuevo proyecto.

**Body**:
```json
{
  "name": "My New Project",
  "description": "Project description",
  "dockerImage": "node:20-alpine",
  "envVars": {
    "NODE_ENV": "production"
  },
  "replicas": 2,
  "cpuLimit": "1000m",
  "memoryLimit": "1Gi"
}
```

**Response**:
```json
{
  "project": {
    "id": "uuid",
    "name": "My New Project",
    "giteaRepoUrl": "http://gitea/owner/my-new-project",
    "k8sNamespace": "my-new-project-abc123"
  }
}
```

### PATCH /projects/:id

Actualiza un proyecto.

### DELETE /projects/:id

Elimina un proyecto y todos sus recursos.

---

## Tasks

### GET /tasks

Lista tareas con filtros opcionales.

**Query params**:
- `projectId`: Filtrar por proyecto
- `state`: Filtrar por estado (`backlog`, `in_progress`, etc.)
- `assignedAgentId`: Filtrar por agente
- `limit`: Límite de resultados (default: 50)
- `offset`: Offset para paginación

**Response**:
```json
{
  "tasks": [
    {
      "id": "uuid",
      "projectId": "uuid",
      "title": "Implement login",
      "description": "Create authentication system",
      "state": "in_progress",
      "priority": "high",
      "assignedAgentId": "agent-123",
      "branchName": "task-abc-implement-login",
      "prNumber": 42,
      "prUrl": "http://gitea/owner/repo/pulls/42",
      "previewUrl": "https://task-abc.preview.aiworker.dev",
      "createdAt": "2026-01-19T10:00:00Z"
    }
  ],
  "total": 10,
  "limit": 50,
  "offset": 0
}
```

### GET /tasks/:id

Obtiene detalles completos de una tarea incluyendo preguntas.

**Response**:
```json
{
  "task": {
    "id": "uuid",
    "title": "Implement login",
    "state": "needs_input",
    "questions": [
      {
        "id": "q-uuid",
        "question": "Which auth library should I use?",
        "context": "Need to choose between JWT or session-based",
        "askedAt": "2026-01-19T11:00:00Z",
        "status": "pending"
      }
    ],
    "project": {
      "name": "My Project",
      "giteaRepoUrl": "..."
    }
  }
}
```

### POST /tasks

Crea una nueva tarea.

**Body**:
```json
{
  "projectId": "uuid",
  "title": "Implement feature X",
  "description": "Detailed description...",
  "priority": "high"
}
```

### PATCH /tasks/:id

Actualiza una tarea.

**Body**:
```json
{
  "state": "approved",
  "notes": "Looks good!"
}
```

### POST /tasks/:id/respond

Responde a una pregunta del agente.

**Body**:
```json
{
  "questionId": "q-uuid",
  "response": "Use JWT with jsonwebtoken library"
}
```

**Response**:
```json
{
  "success": true,
  "question": {
    "id": "q-uuid",
    "status": "answered",
    "respondedAt": "2026-01-19T11:05:00Z"
  }
}
```

### POST /tasks/:id/approve

Aprueba una tarea en estado `ready_to_test`.

### POST /tasks/:id/reject

Rechaza una tarea y la regresa a `in_progress`.

**Body**:
```json
{
  "reason": "Needs more tests"
}
```

---

## Task Groups (Merges)

### POST /task-groups

Crea un grupo de tareas para merge a staging/production.

**Body**:
```json
{
  "projectId": "uuid",
  "taskIds": ["task-1", "task-2", "task-3"],
  "targetBranch": "staging",
  "notes": "Sprint 1 features"
}
```

**Response**:
```json
{
  "taskGroup": {
    "id": "uuid",
    "taskIds": ["task-1", "task-2", "task-3"],
    "status": "pending",
    "stagingBranch": "release/sprint-1"
  }
}
```

### GET /task-groups/:id

Obtiene detalles de un task group.

### POST /task-groups/:id/deploy-staging

Despliega el task group a staging.

### POST /task-groups/:id/deploy-production

Despliega el task group a production.

---

## Agents

### GET /agents

Lista todos los agentes.

**Response**:
```json
{
  "agents": [
    {
      "id": "agent-123",
      "podName": "claude-agent-abc123",
      "status": "busy",
      "currentTaskId": "task-uuid",
      "capabilities": ["javascript", "react", "node"],
      "tasksCompleted": 42,
      "lastHeartbeat": "2026-01-19T12:00:00Z"
    }
  ]
}
```

### GET /agents/:id

Obtiene detalles de un agente incluyendo logs recientes.

### GET /agents/:id/logs

Obtiene logs del agente.

**Query params**:
- `limit`: Número de logs (default: 100)
- `level`: Filtrar por nivel (`debug`, `info`, `warn`, `error`)

---

## Deployments

### GET /deployments

Lista deployments con filtros.

**Query params**:
- `projectId`: Filtrar por proyecto
- `environment`: Filtrar por entorno
- `status`: Filtrar por estado

### GET /deployments/:id

Obtiene detalles de un deployment.

### POST /deployments/:id/rollback

Hace rollback de un deployment.

**Response**:
```json
{
  "success": true,
  "rollbackDeploymentId": "new-uuid"
}
```

---

## Health & Status

### GET /health

Health check del backend.

**Response**:
```json
{
  "status": "ok",
  "timestamp": "2026-01-19T12:00:00Z",
  "services": {
    "mysql": "connected",
    "redis": "connected",
    "gitea": "reachable",
    "kubernetes": "connected"
  },
  "version": "1.0.0"
}
```

### GET /metrics

Métricas del sistema (Prometheus format).

---

## WebSocket Events

Conectar a: `ws://localhost:3000`

### Client → Server

```json
{
  "event": "auth",
  "data": {
    "token": "jwt-token"
  }
}
```

```json
{
  "event": "subscribe",
  "data": {
    "projectId": "uuid"
  }
}
```

### Server → Client

```json
{
  "event": "task:created",
  "data": {
    "taskId": "uuid",
    "projectId": "uuid",
    "title": "New task"
  }
}
```

```json
{
  "event": "task:status_changed",
  "data": {
    "taskId": "uuid",
    "oldState": "in_progress",
    "newState": "ready_to_test",
    "previewUrl": "https://..."
  }
}
```

```json
{
  "event": "task:needs_input",
  "data": {
    "taskId": "uuid",
    "questionId": "q-uuid",
    "question": "Which library?"
  }
}
```

```json
{
  "event": "agent:status",
  "data": {
    "agentId": "agent-123",
    "status": "idle",
    "lastTaskId": "task-uuid"
  }
}
```

```json
{
  "event": "deploy:started",
  "data": {
    "deploymentId": "uuid",
    "environment": "staging"
  }
}
```

```json
{
  "event": "deploy:completed",
  "data": {
    "deploymentId": "uuid",
    "environment": "staging",
    "url": "https://staging-project.aiworker.dev"
  }
}
```

---

## Error Responses

Todos los endpoints pueden retornar estos errores:

### 400 Bad Request
```json
{
  "error": "Validation error",
  "details": {
    "field": "projectId",
    "message": "Required"
  }
}
```

### 401 Unauthorized
```json
{
  "error": "Invalid or expired token"
}
```

### 404 Not Found
```json
{
  "error": "Resource not found"
}
```

### 500 Internal Server Error
```json
{
  "error": "Internal server error",
  "requestId": "req-uuid"
}
```
