const jwt = require('jsonwebtoken');
const Admin = require('../models/Admin');
const { connectDB, getConnection } = require('../config/database');


const authMiddleware = async (req, res, next) => {
  try {
    const token = req.header('Authorization')?.replace('Bearer ', '');
    
    if (!token) {
      return res.status(401).json({ 
        success: false, 
        message: 'Fuck of!'
      });
    }

    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    const connection = getConnection();
    const [admins] = await connection.execute('SELECT * FROM admins WHERE id = ?', [decoded.id]);
    const admin = admins[0];
    if (!admin) {
      return res.status(401).json({ 
        success: false, 
        message: 'Geçersiz token.' 
      });
    }

    req.admin = admin;
    next();
  } catch (error) {
    console.error('Auth middleware error:', error);
    res.status(401).json({ 
      success: false, 
      message: 'Geçersiz token.' 
    });
  }
};

module.exports = authMiddleware;