/**
 * tkuser-api - 사용자 관리 서비스
 *
 * 사용자 CRUD + 페이지 권한 관리 통합 API
 * MariaDB (sso_users + user_page_permissions) 직접 연결
 */

const express = require('express');
const path = require('path');
const cors = require('cors');
const userRoutes = require('./routes/userRoutes');
const permissionRoutes = require('./routes/permissionRoutes');
const projectRoutes = require('./routes/projectRoutes');
const workerRoutes = require('./routes/workerRoutes');
const departmentRoutes = require('./routes/departmentRoutes');
const workplaceRoutes = require('./routes/workplaceRoutes');
const equipmentRoutes = require('./routes/equipmentRoutes');
const taskRoutes = require('./routes/taskRoutes');
const vacationRoutes = require('./routes/vacationRoutes');
const vacationSettingsRoutes = require('./routes/vacationSettingsRoutes');
const partnerRoutes = require('./routes/partnerRoutes');
const vendorRoutes = require('./routes/vendorRoutes');
const consumableItemRoutes = require('./routes/consumableItemRoutes');
const notificationRecipientRoutes = require('./routes/notificationRecipientRoutes');
const notificationRoutes = require('./routes/notificationRoutes');
const pushSubscriptionRoutes = require('./routes/pushSubscriptionRoutes');

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

const allowedOrigins = [
  'https://tkfb.technicalkorea.net',
  'https://tkreport.technicalkorea.net',
  'https://tkqc.technicalkorea.net',
  'https://tkuser.technicalkorea.net',
  'https://tkpurchase.technicalkorea.net',
  'https://tksafety.technicalkorea.net',
  'https://tksupport.technicalkorea.net',
];
if (process.env.NODE_ENV === 'development') {
  allowedOrigins.push('http://localhost:30080', 'http://localhost:30180', 'http://localhost:30280');
}
app.use(cors({
  origin: function(origin, cb) {
    if (!origin || allowedOrigins.includes(origin) || /^http:\/\/192\.168\.\d+\.\d+(:\d+)?$/.test(origin)) return cb(null, true);
    cb(new Error('CORS blocked: ' + origin));
  },
  credentials: true
}));
app.use(express.json());
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// Health check
app.get('/health', (req, res) => {
  res.json({ status: 'ok', service: 'tkuser-api', timestamp: new Date().toISOString() });
});

// Routes
app.use('/api/users', userRoutes);
app.use('/api/permissions', permissionRoutes);
app.use('/api/projects', projectRoutes);
app.use('/api/workers', workerRoutes);
app.use('/api/departments', departmentRoutes);
app.use('/api/workplaces', workplaceRoutes);
app.use('/api/equipments', equipmentRoutes);
app.use('/api/tasks', taskRoutes);
app.use('/api/vacations', vacationRoutes);
app.use('/api/vacation-settings', vacationSettingsRoutes);
app.use('/api/partners', partnerRoutes);
app.use('/api/vendors', vendorRoutes);
app.use('/api/consumable-items', consumableItemRoutes);
app.use('/api/notification-recipients', notificationRecipientRoutes);
app.use('/api/notifications', notificationRoutes);
app.use('/api/push', pushSubscriptionRoutes);

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

// Error handler
app.use((err, req, res, next) => {
  console.error('tkuser-api Error:', err.message);
  res.status(err.status || 500).json({
    success: false,
    error: err.message || 'Internal Server Error'
  });
});

// Startup: 마이그레이션 완료 후 서버 시작
async function start() {
  try {
    const { runMigration, runGenericMigration } = require('./models/vacationSettingsModel');
    await runMigration();
    await runGenericMigration('20260323_add_resigned_date.sql');
    await runGenericMigration('20260326_add_product_types.sql');
  } catch (err) {
    if (!['ER_DUP_FIELDNAME', 'ER_TABLE_EXISTS_ERROR', 'ER_DUP_KEYNAME'].includes(err.code)) {
      console.error('Fatal migration error:', err.message);
      process.exit(1);
    }
    console.error('Migration warning (ignored):', err.message);
  }
  app.listen(PORT, () => {
    console.log(`tkuser-api running on port ${PORT}`);
  });
}
start();

// 오래된 알림 정리 cron (매일 03:00 KST)
(function scheduleNotificationCleanup() {
  const notificationModel = require('./models/notificationModel');
  function runCleanup() {
    const now = new Date();
    const kstHour = (now.getUTCHours() + 9) % 24;
    if (kstHour === 3 && now.getMinutes() < 1) {
      notificationModel.deleteOld(30).then(count => {
        if (count > 0) console.log(`오래된 알림 ${count}건 정리 완료`);
      }).catch(err => {
        console.error('알림 정리 실패:', err.message);
      });
    }
  }
  setInterval(runCleanup, 60000);
})();

module.exports = app;
