/**
 * SSO Auth Service - 중앙 인증 서비스
 *
 * TK Factory Services의 통합 인증을 담당
 * - JWT 발급/검증/갱신
 * - 사용자 CRUD
 * - bcrypt + pbkdf2 비밀번호 호환
 */

const express = require('express');
const cors = require('cors');
const authRoutes = require('./routes/authRoutes');
const { initRedis } = require('./utils/redis');

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',
  'https://tkds.technicalkorea.net',
];
if (process.env.NODE_ENV === 'development') {
  allowedOrigins.push('http://localhost:30000', 'http://localhost:30080', 'http://localhost:30180', 'http://localhost:30280', 'http://localhost:30380');
}
app.use(cors({
  origin: function(origin, cb) {
    if (!origin || allowedOrigins.includes(origin) || /^http:\/\/(192\.168\.\d+\.\d+|localhost)(:\d+)?$/.test(origin)) return cb(null, true);
    cb(new Error('CORS blocked: ' + origin));
  },
  credentials: true
}));
app.use(express.json());

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

// Auth routes
app.use('/api/auth', authRoutes);

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

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

app.listen(PORT, async () => {
  await initRedis();
  console.log(`SSO Auth Service running on port ${PORT}`);
});

module.exports = app;
