import { d as db, a as adminUsers } from '../../admin/create-upload-progress-table/POST-C-OoiMoW.js';
import { eq } from 'drizzle-orm';
import bcrypt from 'bcrypt';

async function handler(req, res) {
  try {
    const { username, password } = req.body;
    if (!username || !password) {
      return res.status(400).json({
        success: false,
        error: "Username and password are required"
      });
    }
    if (typeof username !== 'string' || typeof password !== 'string') {
      return res.status(400).json({ success: false, error: "Invalid input types" });
    }
    if (username.length > 64) {
      return res.status(400).json({ success: false, error: "Username too long" });
    }
    if (password.length > 256) {
      return res.status(400).json({ success: false, error: "Password too long" });
    }
    const users = await db.select().from(adminUsers).where(eq(adminUsers.username, username)).limit(1);
    if (users.length === 0) {
      return res.status(401).json({
        success: false,
        error: "Invalid username or password"
      });
    }
    const user = users[0];
    if (!user.isActive) {
      return res.status(403).json({
        success: false,
        error: "Account is disabled"
      });
    }
    const passwordMatch = await bcrypt.compare(password, user.passwordHash);
    if (!passwordMatch) {
      return res.status(401).json({
        success: false,
        error: "Invalid username or password"
      });
    }
    res.json({
      success: true,
      message: "Login successful",
      user: {
        id: user.id,
        username: user.username,
        email: user.email,
        fullName: user.fullName,
        role: user.role
      }
    });
  } catch (error) {
    console.error("Login failed:", error);
    res.status(500).json({
      success: false,
      error: "Login failed",
      message: String(error)
    });
  }
}

export { handler as h };
