/**
 * Document Security Routes
 * Watermarking, encryption, access control
 */

import { FastifyInstance } from 'fastify';
import { authenticateJWT, requireRole } from '@the-order/shared';
import { addWatermark, redactDocument } from '../services/document-security';

export async function registerSecurityRoutes(server: FastifyInstance): Promise<void> {
  server.post<{ Params: { id: string }; Body: { text: string } }>(
    '/documents/:id/watermark',
    {
      preHandler: [authenticateJWT, requireRole('admin', 'attorney')],
      schema: {
        params: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] },
        body: { type: 'object', properties: { text: { type: 'string' } }, required: ['text'] },
        tags: ['security'],
      },
    },
    async (request, reply) => {
      const { id } = request.params;
      const { text } = request.body;
      const user_id = (request as any).user?.id ?? 'system';
      await addWatermark(id, text, user_id);
      return reply.send({ message: 'Watermark applied' });
    }
  );

  server.post<{
    Params: { id: string };
    Body: { redactions: Array<{ page: number; x: number; y: number; width: number; height: number; reason?: string }> };
  }>('/documents/:id/redact', {
    preHandler: [authenticateJWT, requireRole('admin', 'attorney')],
    schema: {
      params: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] },
      body: { type: 'object', properties: { redactions: { type: 'array' } }, required: ['redactions'] },
      tags: ['security'],
    },
  }, async (request, reply) => {
    const { id } = request.params;
    const { redactions } = request.body;
    const user_id = (request as any).user?.id ?? 'system';
    await redactDocument(id, redactions, user_id);
    return reply.send({ message: 'Redaction applied' });
  });
}

