const express = require('express');
const cors = require('cors');
const cron = require('node-cron');
const dailyVisitRoutes = require('./routes/dailyVisitRoutes');
const educationRoutes = require('./routes/educationRoutes');
const visitRequestRoutes = require('./routes/visitRequestRoutes');
const checklistRoutes = require('./routes/checklistRoutes');
const riskRoutes = require('./routes/riskRoutes');
const dailyVisitModel = require('./models/dailyVisitModel');
const visitRequestModel = require('./models/visitRequestModel');
const riskModel = require('./models/riskModel');
const { requireAuth } = require('./middleware/auth');

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',
];
if (process.env.NODE_ENV === 'development') {
  allowedOrigins.push('http://localhost:30080', 'http://localhost:30580');
}
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());

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

// Routes
app.use('/api/daily-visits', dailyVisitRoutes);
app.use('/api/education', educationRoutes);
app.use('/api/visit-requests', visitRequestRoutes);
app.use('/api/checklist', checklistRoutes);
app.use('/api/risk', riskRoutes);

// Partner search (autocomplete)
app.get('/api/partners/search', requireAuth, async (req, res) => {
  try {
    const q = req.query.q || '';
    if (!q.trim()) return res.json({ success: true, data: [] });
    const db = dailyVisitModel.getPool();
    const [rows] = await db.query(
      'SELECT id, company_name, business_number FROM partner_companies WHERE is_active = TRUE AND company_name LIKE ? ORDER BY company_name LIMIT 20',
      [`%${q}%`]
    );
    res.json({ success: true, data: rows });
  } catch (err) {
    console.error('Partner search error:', err);
    res.status(500).json({ success: false, error: err.message });
  }
});

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

// Error handler
app.use((err, req, res, next) => {
  console.error('tksafety-api Error:', err.message);
  res.status(err.status || 500).json({
    success: false,
    error: '서버 오류가 발생했습니다'
  });
});

// 자정 자동 체크아웃 (매일 23:59 KST)
cron.schedule('59 23 * * *', async () => {
  try {
    const result = await dailyVisitModel.autoCheckoutAll();
    console.log(`Auto checkout: ${result.affectedRows} visits`);
  } catch (e) {
    console.error('Auto checkout failed:', e);
  }
}, { timezone: 'Asia/Seoul' });

app.listen(PORT, async () => {
  console.log(`tksafety-api running on port ${PORT}`);
  // DB 마이그레이션 실행
  try {
    await visitRequestModel.runMigration();
    await riskModel.runMigration();
  } catch (err) {
    console.error('Migration error:', err.message);
  }
});

module.exports = app;
