import { createApp } from './app';
import { env } from './config/env';
import { startReminderScheduler } from './modules/settings/reminder-engine';
import { startCollectionScheduler } from './modules/payments/collections.service';
import { verifyEmailTransport } from './lib/email';
import { startCrmScheduler } from './modules/crm/crm-jobs';
import { startBlogScheduler } from './modules/blog-cms/blog-jobs';
import { startBugTrackerScheduler } from './modules/bug-tracker/bug-jobs';

const app = createApp();

const server = app.listen(env.PORT, () => {
  // eslint-disable-next-line no-console
  console.log(`🚀 HostelCare backend listening on http://localhost:${env.PORT} [${env.NODE_ENV}]`);
});

// Say at boot whether mail will actually go out, so a bad SMTP password is
// found now rather than by the first student who never gets a code.
void verifyEmailTransport().then(({ ok, detail }) => {
  // eslint-disable-next-line no-console
  console.log(`${ok ? '✉️  email ready:' : '⚠️  email NOT ready:'} ${detail}`);
});

// Dues reminders tick hourly in-process; the ReminderLog's unique constraint
// makes every run idempotent, so multiple instances are safe too.
startReminderScheduler();
// Online collection: re-check pending links every ten minutes and compare a
// day's gateway payments nightly. No-op until Razorpay is configured.
startCollectionScheduler();
// CRM: empty the contacts bin of anything older than 30 days, hourly.
startCrmScheduler();
// Website blog: scheduled posts go live and website builds are followed, every minute.
startBlogScheduler();
// Bug tracker: hourly, remove files uploaded for a report nobody sent.
startBugTrackerScheduler();

// Graceful shutdown
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
  process.on(signal, () => {
    // eslint-disable-next-line no-console
    console.log(`\n${signal} received, shutting down...`);
    server.close(() => process.exit(0));
  });
}
