import "server-only";
import { query } from "../connection";

export type ActivityRow = {
  id: number;
  tenant_id: number | null;
  tenant_slug: string | null;
  tenant_name: string | null;
  type: string | null;
  title: string | null;
  description: string | null;
  user_id: number | null;
  user_name: string | null; // dérivé via jointure techniciens
  created_at: Date;
};

// Cross-tenant — on left-join sur tenants pour le contexte et sur techniciens
// pour identifier l'auteur. Limit à 100 lignes pour le V1, on paginera plus
// tard si le journal devient gros.
export async function listActivities(limit = 100): Promise<ActivityRow[]> {
  return query<ActivityRow>(
    `SELECT
       a.id, a.tenant_id, a.type, a.title, a.description,
       a.user_id, a.created_at,
       tn.slug AS tenant_slug,
       tn.name AS tenant_name,
       CONCAT_WS(' ', t.prenom, t.nom) AS user_name
     FROM activities_log a
     LEFT JOIN tenants tn ON tn.id = a.tenant_id
     LEFT JOIN techniciens t ON t.id = a.user_id
     ORDER BY a.created_at DESC, a.id DESC
     LIMIT ?`,
    [limit],
  );
}
