const express = require("express");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const Authrouter = express.Router();
const Admin = require("../models/Admin"); // We'll create this model

const JWT_SECRET = process.env.JWT_SECRET || "your-secret-key-here";

// Register route
Authrouter.post("/admin-register", async (req, res) => {
    try {
        const { username, email, password } = req.body;
      console.log(req.body)
        // Validation
        if (!username || !email || !password) {
            return res.status(400).json({
                success: false,
                message: "All fields are required: username, email, password"
            });
        }

        // Check if admin already exists
        const existingAdmin = await Admin.findOne({ 
            $or: [{ email }, { username }] 
        });

        if (existingAdmin) {
            return res.status(400).json({
                success: false,
                message: "Admin with this email or username already exists"
            });
        }

        // Hash password
        const saltRounds = 10;
        const hashedPassword = await bcrypt.hash(password, saltRounds);

        // Create new admin
        const newAdmin = new Admin({
            username,
            email,
            password: hashedPassword
        });

        // Save admin to database
        await newAdmin.save();

        // Generate JWT token
        const token = jwt.sign(
            { 
                id: newAdmin._id,
                username: newAdmin.username,
                email: newAdmin.email
            },
            JWT_SECRET
        );

        res.status(201).json({
            success: true,
            message: "Admin registered successfully",
            data: {
                id: newAdmin._id,
                username: newAdmin.username,
                email: newAdmin.email,
                token: token
            }
        });

    } catch (error) {
        console.error("Registration error:", error);
        res.status(500).json({
            success: false,
            message: "Internal server error during registration"
        });
    }
});

// Login route
Authrouter.post("/admin-login", async (req, res) => {
    try {
        const { email, password } = req.body;

        // Validation
        if (!email || !password) {
            return res.status(400).json({
                success: false,
                message: "Email and password are required"
            });
        }

        // Find admin by email
        const admin = await Admin.findOne({ email });
        if (!admin) {
            return res.status(401).json({
                success: false,
                message: "Invalid email or password"
            });
        }

        // Check password
        const isPasswordValid = await bcrypt.compare(password, admin.password);
        if (!isPasswordValid) {
            return res.status(401).json({
                success: false,
                message: "Invalid email or password"
            });
        }

        // Generate JWT token
        const token = jwt.sign(
            { 
                id: admin._id,
                username: admin.username,
                email: admin.email
            },
            JWT_SECRET
        );

        res.status(200).json({
            success: true,
            message: "Login successful",
            data: {
                id: admin._id,
                username: admin.username,
                email: admin.email,
                token: token
            }
        });

    } catch (error) {
        console.error("Login error:", error);
        res.status(500).json({
            success: false,
            message: "Internal server error during login"
        });
    }
});

// admin profile
Authrouter.get("/admin-profile/:id",async(req,res)=>{
    try {
        const adminprofile=await Admin.findById({_id:req.params.id});
        if(!adminprofile){
              return res.send({success:false,message:"Admin do not find!"})
        }
        res.send({success:true,data:adminprofile})
    } catch (err) {
        console.log(err) 
    }
})
module.exports = Authrouter;