/**
 * Clause Library Routes
 * Reusable clause management
 */

import { FastifyInstance } from 'fastify';
import {
  createClause,
  getClause,
  getClauseByName,
  listClauses,
  updateClause,
  createClauseVersion,
  renderClause,
  getClauseUsageStats,
} from '@the-order/database';
import { authenticateJWT, requireRole } from '@the-order/shared';

export async function registerClauseRoutes(server: FastifyInstance): Promise<void> {
  server.post('/clauses', {
    preHandler: [authenticateJWT, requireRole('admin', 'attorney')],
    schema: {
      body: {
        type: 'object',
        required: ['name', 'clause_text'],
        properties: {
          name: { type: 'string' },
          title: { type: 'string' },
          clause_text: { type: 'string' },
          category: { type: 'string' },
          tags: { type: 'array', items: { type: 'string' } },
        },
      },
      tags: ['clauses'],
    },
  }, async (request, reply) => {
    const body = request.body as any;
    const user = (request as any).user;
    const clause = await createClause({ ...body, created_by: user?.id });
    return reply.code(201).send(clause);
  });

  server.get('/clauses/:id', {
    preHandler: [authenticateJWT],
    schema: { params: { type: 'object', properties: { id: { type: 'string' } } }, tags: ['clauses'] },
  }, async (request, reply) => {
    const { id } = request.params as { id: string };
    const clause = await getClause(id);
    if (!clause) return reply.code(404).send({ error: 'Clause not found' });
    return reply.send(clause);
  });

  server.get('/clauses', {
    preHandler: [authenticateJWT],
    schema: {
      querystring: {
        type: 'object',
        properties: {
          category: { type: 'string' },
          search: { type: 'string' },
          tags: { type: 'array', items: { type: 'string' } },
        },
      },
      tags: ['clauses'],
    },
  }, async (request, reply) => {
    const query = request.query as any;
    const clauses = await listClauses(query);
    return reply.send({ clauses });
  });

  server.post('/clauses/:id/render', {
    preHandler: [authenticateJWT],
    schema: {
      params: { type: 'object', properties: { id: { type: 'string' } } },
      body: { type: 'object', required: ['variables'], properties: { variables: { type: 'object' } } },
      tags: ['clauses'],
    },
  }, async (request, reply) => {
    const { id } = request.params as { id: string };
    const { variables } = request.body as { variables: Record<string, unknown> };
    const clause = await getClause(id);
    if (!clause) return reply.code(404).send({ error: 'Clause not found' });
    const rendered = renderClause(clause, variables);
    return reply.send({ rendered });
  });
}

