import 'dotenv/config';
import { createServer } from 'http';
import { Server } from 'socket.io';
import app from './app';
import { setupSocketHandlers } from './socket';
import { prisma } from './lib/prisma';
import { ensureLocalDirs } from './lib/ensureLocalDirs';
import { getProjectRoot, getHrSeedPath, getUploadDir } from './lib/projectPaths';

const PORT = Number(process.env.PORT) || 4000;
const FRONTEND_URL = process.env.FRONTEND_URL || 'http://localhost:3000';

const httpServer = createServer(app);

const io = new Server(httpServer, {
  cors: {
    origin: (_origin, callback) => callback(null, true),
    credentials: true,
  },
});

setupSocketHandlers(io);
app.set('io', io);

async function main() {
  ensureLocalDirs();
  await prisma.$connect();
  console.log('✅ Database connected — local PostgreSQL (data/postgres)');

  console.log(`📂 Project root: ${getProjectRoot()}`);
  console.log(`📂 HR seed: ${getHrSeedPath()}`);
  console.log(`📂 Uploads: ${getUploadDir()}`);

  httpServer.listen(PORT, '0.0.0.0', () => {
    console.log(`✅ Server running on http://0.0.0.0:${PORT}  (팀원: http://<이PC의IP>:${PORT})`);
    console.log(`✅ Socket.io ready`);
  });
}

main().catch((err) => {
  console.error('Failed to start server:', err);
  process.exit(1);
});
