/**
 * Legal Documents Service
 * Comprehensive document management for law firms and courts
 */

import Fastify, { type FastifyInstance } from 'fastify';
import fastifySwagger from '@fastify/swagger';
import fastifySwaggerUI from '@fastify/swagger-ui';
import {
  errorHandler,
  createLogger,
  registerSecurityPlugins,
  addCorrelationId,
  addRequestLogging,
  getEnv,
} from '@the-order/shared';
import { getPool } from '@the-order/database';

// Import route handlers
import { registerDocumentRoutes } from './routes/document-routes';
import { registerVersionRoutes } from './routes/version-routes';
import { registerTemplateRoutes } from './routes/template-routes';
import { registerMatterRoutes } from './routes/matter-routes';
import { registerAssemblyRoutes } from './routes/assembly-routes';
import { registerCollaborationRoutes } from './routes/collaboration-routes';
import { registerWorkflowRoutes } from './routes/workflow-routes';
import { registerFilingRoutes } from './routes/filing-routes';
import { registerAuditRoutes } from './routes/audit-routes';
import { registerSearchRoutes } from './routes/search-routes';
import { registerSecurityRoutes } from './routes/security-routes';
import { registerRetentionRoutes } from './routes/retention-routes';
import { registerClauseRoutes } from './routes/clause-routes';

const logger = createLogger('legal-documents-service');

const server: FastifyInstance = Fastify({
  logger: logger as any,
  requestIdLogLabel: 'requestId',
  disableRequestLogging: false,
});

// Initialize database pool
const env = getEnv();
if (env.DATABASE_URL) {
  getPool({ connectionString: env.DATABASE_URL });
}

// Initialize server
async function initializeServer(): Promise<void> {
  // Register Swagger
  const swaggerUrl =
    env.SWAGGER_SERVER_URL ||
    (env.NODE_ENV === 'development' ? 'http://localhost:4005' : undefined);
  if (swaggerUrl) {
    await server.register(fastifySwagger, {
      openapi: {
        info: {
          title: 'Legal Documents Service API',
          description: 'Comprehensive document management for law firms and courts',
          version: '1.0.0',
        },
        servers: [
          {
            url: swaggerUrl,
            description: env.NODE_ENV || 'Development server',
          },
        ],
      },
    });

    await server.register(fastifySwaggerUI, {
      routePrefix: '/docs',
    });
  }

  await registerSecurityPlugins(server as any);
  addCorrelationId(server as any);
  addRequestLogging(server as any);
  server.setErrorHandler(errorHandler as any);

  // Register all routes
  await registerDocumentRoutes(server);
  await registerVersionRoutes(server);
  await registerTemplateRoutes(server);
  await registerMatterRoutes(server);
  await registerAssemblyRoutes(server);
  await registerCollaborationRoutes(server);
  await registerWorkflowRoutes(server);
  await registerFilingRoutes(server);
  await registerAuditRoutes(server);
  await registerSearchRoutes(server);
  await registerSecurityRoutes(server);
  await registerRetentionRoutes(server);
  await registerClauseRoutes(server);
}

// Health check
server.get(
  '/health',
  {
    schema: {
      description: 'Health check endpoint',
      tags: ['health'],
      response: {
        200: {
          type: 'object',
          properties: {
            status: { type: 'string' },
            service: { type: 'string' },
            timestamp: { type: 'string' },
          },
        },
      },
    },
  },
  async (request, reply) => {
    return reply.send({
      status: 'healthy',
      service: 'legal-documents',
      timestamp: new Date().toISOString(),
    });
  }
);

// Start server
async function start(): Promise<void> {
  try {
    await initializeServer();
    const port = env.PORT ? parseInt(env.PORT, 10) : 4005;
    const host = env.HOST || '0.0.0.0';

    await server.listen({ port, host });
    logger.info(`Legal Documents Service listening on ${host}:${port}`);
    logger.info(`Swagger documentation available at http://${host}:${port}/docs`);
  } catch (err) {
    logger.error('Error starting server:', err);
    process.exit(1);
  }
}

// Handle graceful shutdown
process.on('SIGTERM', async () => {
  logger.info('SIGTERM received, shutting down gracefully');
  await server.close();
  process.exit(0);
});

process.on('SIGINT', async () => {
  logger.info('SIGINT received, shutting down gracefully');
  await server.close();
  process.exit(0);
});

if (require.main === module) {
  start().catch((err) => {
    logger.error('Fatal error:', err);
    process.exit(1);
  });
}

export default server;

