const express = require('express');
const cors = require('cors');
const dotenv = require('dotenv');
const bcrypt = require('bcryptjs');
const path = require('path');
const db = require('./config/db.js');
const Admin = require('./models/Admin.js');
const authRoutes = require('./routes/authRoutes.js');
const videoRoutes = require('./routes/videoRoutes.js');
const bhajanRoutes = require('./routes/bhajanRoutes.js');

dotenv.config();

const app = express();

// Middlewares
app.use(cors());
app.use(express.json());
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// Seed default admin if none exist
const seedDefaultAdmin = async () => {
  try {
    const adminCount = await Admin.count();
    if (adminCount === 0) {
      const defaultUsername = 'admin';
      const defaultPassword = 'admin';
      const salt = await bcrypt.genSalt(10);
      const hashedPassword = await bcrypt.hash(defaultPassword, salt);
      await Admin.create({ username: defaultUsername, password: hashedPassword });
      console.log(`Default admin account seeded successfully. Username: "${defaultUsername}", Password: "${defaultPassword}"`);
    } else {
      console.log('Admin accounts already exist. Seeding skipped.');
    }
  } catch (error) {
    console.error('Error seeding default admin:', error);
  }
};

// Seed admin on startup
(async () => {
  await seedDefaultAdmin();
})().catch(err => console.error(err));

// Routes
app.use('/api/auth', authRoutes);
app.use('/api/videos', videoRoutes);
app.use('/api/bhajans', bhajanRoutes);

// Latest route
const { getLatest } = require('./controllers/videoController.js');
const authMiddleware = require('./middleware/authMiddleware.js');
app.get('/api/latest', getLatest);

// Root route
app.get('/', (req, res) => {
  res.json({ message: 'Vedant Devotions SQL API is running.' });
});

// Start Server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});
