import 'reflect-metadata';
import * as nodeCrypto from 'crypto';
if (!(globalThis as any).crypto) {
    (globalThis as any).crypto = nodeCrypto;
}
import { ensureAttachmentsTmpDir } from './time-and-attendance/attachments/config/attachment.fs';
import { NestFactory, Reflector } from '@nestjs/core';
import { AppModule } from './app.module';
import { ModulesGuard } from './common/guards/modules.guard';
import * as session from 'express-session';
import * as passport from 'passport';
import { PrismaSessionStore } from '@quixo3/prisma-session-store';
import { PrismaPostgresService } from 'prisma/postgres/prisma-postgres.service';

const SESSION_TOKEN_DURATION_MINUTES = 180

async function bootstrap() {
    const app = await NestFactory.create(AppModule);
    const prisma_postgres = app.get(PrismaPostgresService);

    const reflector = app.get(Reflector);

    app.useGlobalGuards(
        new ModulesGuard(reflector), //deny-by-default and Module-based Access Control
    );

    // Authentication and session
    app.use(session({
        secret: 'This is a super secret dev secret that you cant share with anyone',
        resave: false,
        saveUninitialized: false,
        rolling: true,
        cookie: {
            maxAge: SESSION_TOKEN_DURATION_MINUTES * 60 * 1000,     // property maxAge requires milliseconds
            httpOnly: true,
        },
        store: new PrismaSessionStore(prisma_postgres, {
            sessionModelName: 'sessions',
            checkPeriod: SESSION_TOKEN_DURATION_MINUTES * 60 * 1000,  //ms
            dbRecordIdIsSessionId: true,
            dbRecordIdFunction: undefined,
        })
    }))
    app.use(passport.initialize());
    app.use(passport.session());

    // Enable CORS
    app.enableCors({
        origin: ['http://10.100.251.2:9011', 'http://10.100.251.2:9012', 'http://10.100.251.2:9013', 'http://localhost:9000', 'https://app.targo.ca', 'https://portail.targo.ca','https://staging.app.targo.ca'],
        credentials: true,
    });

    await ensureAttachmentsTmpDir();
    await app.listen(process.env.PORT ?? 3000);


    // migration function calls
    // await initializePaidTimeOff();
    // await initializePreferences();
    // await extractOldTimesheets();
    // await extractOldShifts();
    // await extractOldExpenses();
    // await initSupervisor();
}
bootstrap();
