import 'reflect-metadata';
import { Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NestFactory } from '@nestjs/core';
import helmet from 'helmet';
import { AppModule } from './app.module';
import { ApprovalService } from './approvals/approval.service';
import { AttachmentService } from './attachments/attachment.service';
import { createUploadsRouter } from './attachments/attachments.adapter';
import { AuthService } from './auth/auth.service';
import { BillingService } from './billing/billing.service';
import { DepositsService } from './deposits/deposits.service';
import { DocumentService } from './documents/document.service';
import { createDocumentsRouter } from './documents/documents.adapter';
import { MaintenanceService } from './maintenance/maintenance.service';
import { createManualRouter } from './manual/manual.adapter';
import { MeteringService } from './metering/metering.service';
import { PaymentsService } from './payments/payments.service';
import { PrismaService } from './prisma/prisma.service';
import { ReportsService } from './reports/reports.service';
import { StatementsService } from './statements/statements.service';
import { createTrpcMiddleware } from './trpc/trpc.adapter';

async function bootstrap(): Promise<void> {
  const app = await NestFactory.create(AppModule, { bufferLogs: false });

  const config = app.get(ConfigService);
  const corsOrigin = config.get<string>('CORS_ORIGIN');

  app.use(helmet());
  // Trust the reverse proxy so per-IP rate limits see the real client IP.
  app.getHttpAdapter().getInstance().set('trust proxy', 1);

  app.setGlobalPrefix('api');
  // Restrict CORS to the configured origin(s) in production; permissive in dev.
  app.enableCors({ origin: corsOrigin ? corsOrigin.split(',').map((o) => o.trim()) : true, credentials: true });
  app.enableShutdownHooks();

  // Mount the tRPC router as raw middleware (outside the Nest controller layer).
  const prisma = app.get(PrismaService);
  const authService = app.get(AuthService);
  const billing = app.get(BillingService);
  const payments = app.get(PaymentsService);
  const deposits = app.get(DepositsService);
  const metering = app.get(MeteringService);
  const maintenance = app.get(MaintenanceService);
  const approvals = app.get(ApprovalService);
  const reports = app.get(ReportsService);
  const documents = app.get(DocumentService);
  const statements = app.get(StatementsService);
  app.use('/api/trpc', createTrpcMiddleware(prisma, authService, billing, payments, deposits, metering, maintenance, approvals, reports, documents, statements));

  // Binary uploads/downloads live outside tRPC (which is JSON-only).
  const attachments = app.get(AttachmentService);
  app.use('/api/uploads', createUploadsRouter(prisma, authService, attachments));

  // Generated PDFs — same reason, same shape.
  app.use('/api/documents', createDocumentsRouter(prisma, authService, documents, reports, statements));

  // The user manual — static bytes, but behind login, because its screenshots
  // name the real landlord companies and their accounting codes.
  app.use('/api/manual', createManualRouter(authService));

  const port = config.get<number>('API_PORT') ?? 3000;

  await app.listen(port);
  new Logger('Bootstrap').log(`RMS API listening on http://localhost:${port}/api`);
}

void bootstrap();
