import { NextResponse } from 'next/server';
import dbConnect from '../../../../src/lib/mongodb';
import User from '../../../../src/models/User';

export async function GET() {
  try {
    await dbConnect();

    const users = await User.find({}).sort({ createdAt: -1 });

    // If no users exist, create some sample data
    if (users.length === 0) {
      const sampleUsers = [
        { name: 'John Doe', email: 'john@example.com', role: 'Admin', status: 'Active' },
        { name: 'Jane Smith', email: 'jane@example.com', role: 'User', status: 'Active' },
        { name: 'Bob Johnson', email: 'bob@example.com', role: 'User', status: 'Inactive' },
      ];

      await User.insertMany(sampleUsers);
      const newUsers = await User.find({}).sort({ createdAt: -1 });
      
      return NextResponse.json({ 
        users: newUsers,
        total: newUsers.length 
      });
    }

    return NextResponse.json({ 
      users,
      total: users.length 
    });
  } catch (error) {
    console.error('Error fetching users:', error);
    return NextResponse.json(
      { error: 'Failed to fetch users' },
      { status: 500 }
    );
  }
}

export async function POST(request: Request) {
  try {
    await dbConnect();

    const body = await request.json();

    // Validate required fields
    if (!body.name || !body.email) {
      return NextResponse.json(
        { error: 'Name and email are required' },
        { status: 400 }
      );
    }

    // Check if user already exists
    const existingUser = await User.findOne({ email: body.email });
    if (existingUser) {
      return NextResponse.json(
        { error: 'User with this email already exists' },
        { status: 409 }
      );
    }

    const newUser = await User.create({
      name: body.name,
      email: body.email,
      role: body.role || 'User',
      status: body.status || 'Active'
    });

    return NextResponse.json({ 
      user: newUser,
      message: 'User created successfully' 
    }, { status: 201 });
  } catch (error) {
    console.error('Error creating user:', error);
    return NextResponse.json(
      { error: 'Failed to create user' },
      { status: 500 }
    );
  }
}
