const express = require("express");
const bcrypt = require("bcrypt");
const router = express.Router();
const {db}= require("../config/dbConfig"); 

// Admin Sign-in Route
router.post("/api/admin-signin", (req, res) => {
  const { username, password } = req.body;

  // Validate environment variables for admin credentials
  if (!process.env.ADMIN_USERNAME || !process.env.ADMIN_PASSWORD) {
    console.error("Admin credentials are not set in environment variables.");
    return res.status(500).json({ message: "Server configuration error" });
  }

  // Check if credentials are correct
  if (username === process.env.ADMIN_USERNAME && password === process.env.ADMIN_PASSWORD) {
    return res.status(200).json({ message: "Admin login successful" });
  } else {
    return res.status(401).json({ message: "Invalid Admin credentials" });
  }
});



router.post('/api/signin', (req, res) => {
  const { mobile, password } = req.body;

  db.query('SELECT * FROM users WHERE mobile = ?', [mobile], async (err, results) => {
    if (err || results.length === 0 || !(await bcrypt.compare(password, results[0].password))) {
      return res.status(400).send('Invalid credentials');
    }

    // If credentials are valid, return the user's name
    const userName = results[0].name;
    
    res.status(200).json({ message: 'Login successful', userName });
  });
});

// User Signup Route
router.post("/api/signup", async (req, res) => {
  const { name, mobile, district, state, password } = req.body;

  // Validate input data
  if (!name || !mobile || !district || !state || !password) {
    return res.status(400).json({ message: "All fields are required" });
  }

  try {
    // Check if a user with the provided mobile number already exists
    db.query("SELECT * FROM users WHERE mobile = ?", [mobile], async (err, results) => {
      if (err) {
        console.error("Error checking for existing user:", err);
        return res.status(500).json({ message: "Server error" });
      }

      if (results.length > 0) {
        return res.status(400).json({ message: "Mobile number already registered" });
      }

      // Hash the password before saving to the database
      const hashedPassword = await bcrypt.hash(password, 10);

      // Insert the new user into the database
      const insertUserQuery = `
        INSERT INTO users (name, mobile, district, state, password) 
        VALUES (?, ?, ?, ?, ?)
      `;
      db.query(insertUserQuery, [name, mobile, district, state, hashedPassword], (err) => {
        if (err) {
          console.error("Error inserting user:", err);
          return res.status(500).json({ message: "Error registering user" });
        }

        res.status(200).json({ message: "User registered successfully" });
      });
    });
  } catch (error) {
    console.error("Error during signup:", error);
    res.status(500).json({ message: "Server error" });
  }
});

module.exports = router;
