import User from "../models/User.js";

// Get all clients (admin only)
export const getAllClients = async (req, res) => {
  try {
    const { search, page = 1, limit = 10 } = req.query;

    let query = { role: "client" };

    // Search by name or email
    if (search) {
      query.$or = [
        { fullName: { $regex: search, $options: "i" } },
        { email: { $regex: search, $options: "i" } }
      ];
    }

    const skip = (parseInt(page) - 1) * parseInt(limit);

    const clients = await User.find(query)
      .select("-password")
      .skip(skip)
      .limit(parseInt(limit))
      .sort({ createdAt: -1 });

    const total = await User.countDocuments(query);

    res.json({
      clients,
      total,
      page: parseInt(page),
      pages: Math.ceil(total / parseInt(limit))
    });
  } catch (error) {
    console.error("Get all clients error:", error);
    res.status(500).json({ message: "Server error" });
  }
};

// Get single client
export const getClient = async (req, res) => {
  try {
    const client = await User.findOne({ _id: req.params.id, role: "client" }).select("-password");
    if (!client) {
      return res.status(404).json({ message: "Client not found" });
    }
    res.json(client);
  } catch (error) {
    console.error("Get client error:", error);
    res.status(500).json({ message: "Server error" });
  }
};

// Create client (admin only)
export const createClient = async (req, res) => {
  try {
    const { fullName, email, phone, password } = req.body;

    // Check if email exists
    const existingUser = await User.findOne({ email });
    if (existingUser) {
      return res.status(400).json({ message: "Email already registered" });
    }

    const client = new User({
      fullName,
      email,
      phone,
      password,
      role: "client"
    });

    await client.save();

    res.status(201).json({
      message: "Client created successfully",
      client: {
        id: client._id,
        fullName: client.fullName,
        email: client.email,
        phone: client.phone,
        role: client.role
      }
    });
  } catch (error) {
    console.error("Create client error:", error);
    res.status(500).json({ message: "Server error" });
  }
};

// Update client
export const updateClient = async (req, res) => {
  try {
    const { fullName, email, phone, password } = req.body;

    const updateData = { fullName, email, phone };
    if (password) {
      updateData.password = password;
    }

    const client = await User.findByIdAndUpdate(
      req.params.id,
      updateData,
      { new: true }
    ).select("-password");

    if (!client) {
      return res.status(404).json({ message: "Client not found" });
    }

    res.json({ message: "Client updated successfully", client });
  } catch (error) {
    console.error("Update client error:", error);
    res.status(500).json({ message: "Server error" });
  }
};

// Delete client
export const deleteClient = async (req, res) => {
  try {
    const client = await User.findOneAndDelete({ _id: req.params.id, role: "client" });
    if (!client) {
      return res.status(404).json({ message: "Client not found" });
    }
    res.json({ message: "Client deleted successfully" });
  } catch (error) {
    console.error("Delete client error:", error);
    res.status(500).json({ message: "Server error" });
  }
};