import type { NextApiRequest, NextApiResponse } from "next" import { db, schema } from "../../../lib/db/connection" import { eq, count, sql } from "drizzle-orm" import * as bcrypt from "bcryptjs" async function hashPassword(password: string): Promise { return await bcrypt.hash(password, 12) } export default async function handler(req: NextApiRequest, res: NextApiResponse) { try { if (req.method === "GET") { const users = await db.select({ id: schema.users.id, email: schema.users.email, role: schema.users.role, isActive: schema.users.isActive, createdAt: schema.users.createdAt, lastLogin: schema.users.lastLogin, sourcesModerated: sql`(SELECT COUNT(*) FROM ${schema.sources} WHERE verified_by = ${schema.users.id})` }) .from(schema.users) .orderBy(schema.users.createdAt) res.json({ users }) } else if (req.method === "POST") { const { email, password, role } = req.body if (!email || !password || !role) { return res.status(400).json({ error: "Email, password and role required" }) } if (!['admin', 'moderator'].includes(role)) { return res.status(400).json({ error: "Invalid role" }) } const passwordHash = await hashPassword(password) const result = await db.insert(schema.users) .values({ email, passwordHash, name: email.split('@')[0], // Use email username as name role: role as 'admin' | 'moderator', isActive: true }) .returning({ id: schema.users.id }) res.json({ success: true, user: { id: result[0].id, email, role, isActive: true } }) } else { res.status(405).json({ error: "Method not allowed" }) } } catch (error: any) { console.error('Users API error:', error) if (error?.code === '23505') { res.status(400).json({ error: "User already exists" }) } else { res.status(500).json({ error: "Operation failed" }) } } }