require('./config/loadEnv')();
const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const path = require('path');

const healthRoutes = require('./routes/health');
const proofRoutes = require('./routes/proof');
const txRoutes = require('./routes/tx');
const blockRoutes = require('./routes/block');
const adminRoutes = require('./routes/admin');
const contractRoutes = require('./routes/contract');
const authStatusRoutes = require('./routes/authStatus');
const nodeRoutes = require('./routes/node');
const backupRoutes = require('./routes/backup');
const callbackRoutes = require('./routes/callback');
const testnetRoutes = require('./routes/testnet');
const homeRoutes = require('./routes/home');
const explorerRoutes = require('./routes/explorer');
const walletRoutes = require('./routes/wallet');
const walletPageRoutes = require('./routes/walletPage');
const rewardRoutes = require('./routes/reward');
const { authenticateAdmin, clearAdminSession, requireAdminAuth, setAdminSession } = require('./middleware/adminAuth');

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

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

app.use(cors());
app.use(morgan('dev', {
  skip: req => String(req.originalUrl || '').startsWith('/wallet/login')
}));
app.use(express.json({ limit: '1mb' }));
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/health', healthRoutes);
app.use('/api/proof', proofRoutes);
app.use('/api/tx', txRoutes);
app.use('/api/block', blockRoutes);
app.use('/api/contract', contractRoutes);
app.use('/api/auth-status', authStatusRoutes);
app.use('/api/node', nodeRoutes);
app.use('/api/backup', backupRoutes);
app.use('/api/callback', callbackRoutes);
app.use('/api/testnet', testnetRoutes);
app.use('/api/wallet', walletRoutes);
app.use('/api/reward', rewardRoutes);
app.use('/wallet', walletPageRoutes);
app.get('/admin/login', (req, res) => {
  res.render('admin_login', {
    nextPath: req.query.next || '/admin',
    error: req.query.error ? '아이디 또는 비밀번호를 확인해 주세요.' : '',
    loggedOut: req.query.loggedOut === '1'
  });
});
app.post('/admin/login', (req, res) => {
  const nextPath = String(req.body.next || '/admin');
  if (!authenticateAdmin(req.body.username, req.body.password)) {
    return res.redirect(`/admin/login?error=1&next=${encodeURIComponent(nextPath)}`);
  }
  setAdminSession(res, req.body.username);
  return res.redirect(nextPath.startsWith('/admin') ? nextPath : '/admin');
});
app.get('/admin/logout', (req, res) => {
  clearAdminSession(res);
  res.redirect('/admin/login?loggedOut=1');
});
app.use('/admin', requireAdminAuth, adminRoutes);
app.use('/explorer', explorerRoutes);
app.use('/', homeRoutes);

app.use((req, res) => {
  res.status(404).json({
    ok: false,
    error: 'NOT_FOUND',
    message: 'Route not found'
  });
});

app.use((err, req, res, next) => {
  if (!err.status || err.status >= 500) {
    console.error(err);
  } else {
    console.warn(`${err.code || 'CLIENT_ERROR'}: ${err.message}`);
  }

  res.status(err.status || 500).json({
    ok: false,
    error: err.code || 'SERVER_ERROR',
    message: err.message || 'Unexpected server error',
    details: err.details || undefined
  });
});

app.listen(PORT, () => {
  console.log(`AISFOR-CHAIN mock server listening on http://localhost:${PORT}`);
});





