const express = require('express');
const dotenv = require('dotenv');
const path = require('path');
const fs = require('fs');
const { authMiddleware } = require('./middleware/auth');
const { apiRoutes } = require('./routes/api');
const { validateConfig } = require('./config');

let resourcePath = process.cwd();

if (require.main && require.main.filename) {
  resourcePath = path.dirname(require.main.filename);
} else {
  try {
    const testPath = require.resolve('./server.js');
    resourcePath = path.dirname(testPath);
  } catch (e) {
    resourcePath = process.cwd();
  }
}

const envPath = path.join(resourcePath, '.env');

if (fs.existsSync(envPath)) {
  dotenv.config({ path: envPath });
  console.log(`^2[ICManager]^7 Loaded .env from: ${envPath}`);
} else {
  dotenv.config();
  console.log(`^3[ICManager]^7 .env not found at ${envPath}, trying default location (${process.cwd()})`);
}

if (process.env.API_KEY) {
  console.log(`^2[ICManager]^7 API_KEY loaded successfully (length: ${process.env.API_KEY.length})`);
} else {
  console.log(`^1[ICManager]^7 WARNING: API_KEY not found in environment variables`);
  console.log(`^3[ICManager]^7 Current working directory: ${process.cwd()}`);
  console.log(`^3[ICManager]^7 Resource directory: ${resourcePath}`);
  console.log(`^3[ICManager]^7 Tried .env path: ${envPath}`);
  
  try {
    const files = fs.readdirSync(resourcePath);
    console.log(`^3[ICManager]^7 Files in resource directory: ${files.join(', ')}`);
  } catch (e) {
    console.log(`^1[ICManager]^7 Could not read resource directory: ${e.message}`);
  }
}

try {
  validateConfig();
} catch (error) {
  console.error('[Server] Configuration validation failed:', error.message);
  process.exit(1);
}

const app = express();
const PORT = process.env.PORT || 3000;

app.disable('x-powered-by');
app.set('trust proxy', 1);

app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

app.get('/health', (req, res) => {
  res.status(200).json({ 
    status: 'ok', 
    timestamp: new Date().toISOString(),
    uptime: process.uptime()
  });
});

app.use('/api', authMiddleware, apiRoutes);

app.use((req, res) => {
  res.status(404).json({ error: 'Not found' });
});

app.use((err, req, res, next) => {
  console.error('Error:', err);
  res.status(err.status || 500).json({ 
    error: process.env.NODE_ENV === 'production' ? 'Internal server error' : err.message 
  });
});

let server;

async function startServer() {
  try {
    server = app.listen(PORT, () => {
      console.log(`^2[ICManager]^7 Server running on port ${PORT}`);
      console.log(`^2[ICManager]^7 Environment: ${process.env.NODE_ENV || 'development'}`);
    });
  } catch (error) {
    console.error(`^1[ICManager]^7 Failed to start server: ${error.message}`);
    process.exit(1);
  }
}

startServer();

const shutdown = async () => {
  console.log('^3[ICManager]^7 Shutting down server...');
  if (server) {
    server.close(() => {
      console.log('^1[ICManager]^7 Server closed');
      process.exit(0);
    });
  } else {
    process.exit(0);
  }
};

process.on('SIGTERM', shutdown);
process.on('SIGINT', shutdown);

module.exports = { app, server, startServer };

