<?php
declare(strict_types=1);

namespace Infolab\Controllers;

use Infolab\Database;
use Infolab\Request;
use Infolab\Response;

/**
 * GET /api/activity — flux pour le dashboard ("Vous a rejoint le projet X").
 * Filtres : ?limit=N (1..100, défaut 20), ?project=slug.
 */
final class ActivityController
{
    public function index(Request $req, array $params): void
    {
        $limit = max(1, min(100, (int) $req->query('limit', 20)));

        $where = '1=1';
        $args  = [];

        $projectSlug = $req->query('project');
        if ($projectSlug !== null && $projectSlug !== '') {
            $pid = Database::fetchValue('SELECT id FROM projects WHERE slug = :s', [':s' => (string) $projectSlug]);
            if ($pid === null) {
                // Projet inconnu : on renvoie un flux vide (pas d'erreur, le slug peut
                // simplement ne pas exister côté serveur — comportement choisi pour
                // simplifier le widget côté front).
                Response::json(['data' => []]);
                return;
            }
            $where         = 'project_id = :pid';
            $args[':pid']  = (int) $pid;
        }

        $rows = Database::fetchAll(
            "SELECT id, project_id, member_id, actor_label, verb, summary, occurred_at
             FROM activity_log WHERE $where
             ORDER BY occurred_at DESC, id DESC LIMIT $limit",
            $args,
        );

        $data = array_map(static fn(array $r): array => [
            'id'          => (int) $r['id'],
            'project_id'  => $r['project_id'] === null ? null : (int) $r['project_id'],
            'member_id'   => $r['member_id']  === null ? null : (int) $r['member_id'],
            'actor_label' => $r['actor_label'],
            'verb'        => $r['verb'],
            'summary'     => $r['summary'],
            'occurred_at' => $r['occurred_at'],
        ], $rows);

        Response::json(['data' => $data]);
    }
}
