const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
require("dotenv").config();
const { PrismaClient } = require("@prisma/client");
const prisma = new PrismaClient();

const generateJwtToken = (userId) => {
  try {
    return jwt.sign({ id: userId }, process.env.JWT_SECRET || "$ecret", {
      expiresIn: "5h",
      algorithm: "HS256",
    });
  } catch (error) {
    console.error("❌ Error generating JWT token:", error.message);
    return null;
  }
};

async function login(req, res) {
  const { email, password } = req.body;

  if (!email || !password) {
    return res.status(400).json({ error: "Email and password are required" });
  }

  try {
    // Find user using Prisma
    const user = await prisma.user.findFirst({
      where: { email }
    });

    if (!user) {
      return res.status(401).json({ error: "No user found" });
    }

    const passwordMatch = await bcrypt.compare(password, user.password);
    if (!passwordMatch) {
      return res.status(401).json({ error: "Invalid email or password" });
    }

    const token = generateJwtToken(user.id);
    if (!token) {
      return res.status(500).json({ error: "Error generating token" });
    }

    res.cookie("jwt", token, {
      httpOnly: true,
      maxAge: 1000 * 60 * 60 * 5, 
    });

    res.status(200).json({
      message: "Login successful",
      user: {
        id: user.id,
        email: user.email
      },
    });
  } catch (err) {
    console.error("❌ Error logging in:", err.message);
    res.status(500).json({ error: "Internal Server Error" });
  }
};

const read = async (id) => {
  try {
    const user = await prisma.user.findUnique({
      where: { id: parseInt(id) },
      include: {
        role: true,
        listings: {
          include: {
            images: true,
            listingType: true,
            pricing: true,
            featureListings: {
              include: {
                feature: true
              }
            }
          }
        }
      }
    });
    return user || null;
  } catch (err) {
    console.error("Error reading user:", err.message);
    throw err;
  }
};

module.exports = { login, read };
