import { NextRequest, NextResponse } from 'next/server';
import { prismaAuth } from '@/lib/db';
import { isAdmin } from '@/lib/permissions';
import bcrypt from 'bcryptjs';
import { isValidEmail } from '@/lib/utils';

// GET /api/users - List all users (admin only)
export async function GET(request: NextRequest) {
  try {
    console.log('[API /users] Request received');
    
    // Check if user is admin
    console.log('[API /users] Checking admin status...');
    const admin = await isAdmin();
    console.log('[API /users] Admin check result:', admin);
    
    if (!admin) {
      console.log('[API /users] Unauthorized - user is not admin');
      return NextResponse.json(
        { error: 'Unauthorized. Admin access required.', message: 'You must be an administrator to access this resource.' },
        { status: 403 }
      );
    }

    console.log('[API /users] User is admin, fetching users from database...');
    
    // Get filter from query parameters
    const { searchParams } = new URL(request.url);
    const statusFilter = searchParams.get('status'); // 'all', 'active', 'inactive'
    
    // Build where clause based on filter
    let whereClause: any = {};
    if (statusFilter === 'active') {
      whereClause = { NOT: { isActive: false } }; // Active only (treat null/undefined as active)
    } else if (statusFilter === 'inactive') {
      whereClause = { isActive: false }; // Inactive only
    }
    // If 'all' or no filter, don't add where clause (get all users)
    
    const users = await prismaAuth.user.findMany({
      where: whereClause,
      select: {
        id: true,
        email: true,
        name: true,
        isAdmin: true,
        hasWriteAccess: true,
        isActive: true,
        createdAt: true,
        updatedAt: true,
      },
      orderBy: {
        createdAt: 'desc',
      },
    });

    console.log('[API /users] Successfully fetched', users.length, 'users');
    return NextResponse.json({ users }, { status: 200 });
  } catch (error: any) {
    console.error('[API /users] Error:', error);
    console.error('[API /users] Error stack:', error.stack);
    return NextResponse.json(
      { 
        error: 'Failed to fetch users', 
        details: error.message,
        message: error.message || 'An unexpected error occurred while fetching users.'
      },
      { status: 500 }
    );
  }
}

// POST /api/users - Create new user (admin only)
export async function POST(request: NextRequest) {
  try {
    // Check if user is admin
    const admin = await isAdmin();
    if (!admin) {
      return NextResponse.json(
        { error: 'Unauthorized. Admin access required.' },
        { status: 403 }
      );
    }

    const body = await request.json();
    const {
      email,
      password,
      name,
      hasWriteAccess,
      isAdmin: newUserIsAdmin,
    } = body;

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

    if (name.trim().length === 0) {
      return NextResponse.json(
        { error: 'Name cannot be empty' },
        { status: 400 }
      );
    }

    if (!isValidEmail(email)) {
      return NextResponse.json(
        { error: 'Please enter a valid email address' },
        { status: 400 }
      );
    }

    if (password.length < 6) {
      return NextResponse.json(
        { error: 'Password must be at least 6 characters' },
        { status: 400 }
      );
    }

    // Check if user already exists
    const existingUser = await prismaAuth.user.findUnique({
      where: { email },
    });

    if (existingUser) {
      return NextResponse.json(
        { error: 'User with this email already exists' },
        { status: 409 }
      );
    }

    // Hash password
    const passwordHash = await bcrypt.hash(password, 10);

    // Create user (admin-created users are automatically verified)
    const user = await prismaAuth.user.create({
      data: {
        email,
        passwordHash,
        name: name.trim(),
        hasWriteAccess: hasWriteAccess ?? false,
        isAdmin: newUserIsAdmin ?? false,
        emailVerified: true, // Admin-created users are automatically verified
        emailConfirmationToken: null, // No confirmation token needed
        emailConfirmationTokenExpiry: null, // No expiry needed
      },
      select: {
        id: true,
        email: true,
        name: true,
        isAdmin: true,
        hasWriteAccess: true,
        createdAt: true,
        updatedAt: true,
      },
    });

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

