import 'dotenv/config'

// Polyfill DOMMatrix for pdf-parse (pdf.js requires browser API)
if (typeof globalThis.DOMMatrix === 'undefined') {
  class DOMMatrixPolyfill {
    a = 1; b = 0; c = 0; d = 1; e = 0; f = 0
    m11 = 1; m12 = 0; m13 = 0; m14 = 0
    m21 = 0; m22 = 1; m23 = 0; m24 = 0
    m31 = 0; m32 = 0; m33 = 1; m34 = 0
    m41 = 0; m42 = 0; m43 = 0; m44 = 1
    is2D = true; isIdentity = true
    constructor(init?: string | number[]) {
      if (typeof init === 'string') {
        const m = init.match(/matrix\(([^)]+)\)/)
        if (m) {
          const v = m[1].split(',').map(Number)
          if (v.length >= 6) { this.a = v[0]; this.b = v[1]; this.c = v[2]; this.d = v[3]; this.e = v[4]; this.f = v[5] }
        }
      }
    }
    multiply(m: DOMMatrixPolyfill) { return this }
    translate(x: number, y: number) { return this }
    scale(s: number) { return this }
    rotate(r: number) { return this }
    toString() { return `matrix(${this.a}, ${this.b}, ${this.c}, ${this.d}, ${this.e}, ${this.f})` }
    toJSON() { return { a: this.a, b: this.b, c: this.c, d: this.d, e: this.e, f: this.f } }
  }
  // @ts-ignore
  globalThis.DOMMatrix = DOMMatrixPolyfill
  // @ts-ignore
  globalThis.DOMMatrixReadOnly = DOMMatrixPolyfill
  // @ts-ignore
  globalThis.DOMPoint = class { x = 0; y = 0; z = 0; w = 1 }
}

import { NestFactory } from '@nestjs/core'
import { ValidationPipe } from '@nestjs/common'
import { AppModule } from './app.module'
import { AllExceptionsFilter } from './common/filters/all-exceptions.filter'

async function bootstrap() {
  const app = await NestFactory.create(AppModule)

  app.setGlobalPrefix('api')
  const allowedOrigins = process.env.CORS_ORIGINS?.split(',') || ['http://localhost:8085', 'http://localhost:3006', 'https://zhiyin.yzrcloud.cn']
  app.enableCors({
    origin: (origin, callback) => {
      if (!origin || allowedOrigins.includes(origin)) {
        callback(null, true)
      } else {
        callback(new Error('Not allowed by CORS'))
      }
    },
    methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
    credentials: true,
  })

  app.useGlobalFilters(new AllExceptionsFilter())
  app.useGlobalPipes(new ValidationPipe({
    whitelist: true,
    forbidNonWhitelisted: true,
    transform: true,
  }))

  const port = process.env.PORT || 3006
  await app.listen(port)
  console.log(`🚀 Server running on http://localhost:${port}`)
}
bootstrap()
