// RGPD (droits d'accès & d'effacement) : export et suppression des données rattachées au token
// authentifié. Modèle mono-utilisateur → le détenteur du token EST le sujet des données. Sous l'auth
// globale. La suppression se fait en deux temps (code de confirmation) pour éviter les clics accidentels.
import { createHash } from 'node:crypto';
import type { FastifyInstance } from 'fastify';
import type { DataExportResponse, DeleteMyDataRequest, DeleteMyDataResponse } from '@arboretum/shared';
import type { Db } from '../db/index.js';
import type { AuthService } from '../auth/service.js';
import { readScanIntervalMin, readScanRoots } from '../core/scan-settings.js';
import { recordAudit } from '../core/audit-log.js';

export function registerDataRoutes(app: FastifyInstance, db: Db, auth: AuthService): void {
  app.get('/api/v1/data/export', async (req): Promise<DataExportResponse> => {
    const current = req.authContext!.tokenId;
    const tokens = auth.listTokens().map((t) => ({ ...t, current: t.id === current }));
    const pushSubscriptions = db
      .prepare(
        'SELECT endpoint, user_agent AS userAgent, created_at AS createdAt, last_ok_at AS lastOkAt FROM push_subscriptions WHERE token_id = ?',
      )
      .all(current) as DataExportResponse['pushSubscriptions'];
    const sessions = db
      .prepare(
        'SELECT id, cwd, command, title, created_at AS createdAt, ended_at AS endedAt, exit_code AS exitCode FROM sessions ORDER BY created_at',
      )
      .all() as DataExportResponse['sessions'];
    return {
      exportedAt: new Date().toISOString(),
      tokens,
      pushSubscriptions,
      sessions,
      settings: { scanRoots: readScanRoots(db), scanIntervalMin: readScanIntervalMin(db) },
    };
  });

  app.post('/api/v1/data/delete-my-data', async (req, reply) => {
    const current = req.authContext!.tokenId;
    // code déterministe lié au token (sans état serveur) : renvoyé au 1er appel, exigé au 2nd.
    const code = createHash('sha256').update(`delete:${current}`).digest('hex').slice(0, 12);
    const body = (req.body as DeleteMyDataRequest | null) ?? {};
    const subsCount = (db.prepare('SELECT COUNT(*) AS n FROM push_subscriptions WHERE token_id = ?').get(current) as { n: number }).n;

    if (body.confirm !== code) {
      const res: DeleteMyDataResponse = { status: 'pending', confirm: code, summary: { pushSubscriptions: subsCount, tokenRevoked: false } };
      return reply.send(res);
    }

    db.prepare('DELETE FROM push_subscriptions WHERE token_id = ?').run(current);
    // révoque le token courant (sauf si c'est le dernier actif → garde anti lock-out conservée).
    const revoked = auth.revokeToken(current) === 'ok';
    recordAudit(db, { actor: current, action: 'data.delete', details: { pushSubscriptions: subsCount, tokenRevoked: revoked } });
    const res: DeleteMyDataResponse = { status: 'done', summary: { pushSubscriptions: subsCount, tokenRevoked: revoked } };
    return reply.send(res);
  });
}
