import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { verifyAdminPermission } from '@/lib/auth';
import { sanitizeString, isValidEmail, isValidId, isValidName } from '@/lib/validation';
import { checkRateLimit, getRateLimitIdentifier, rateLimitError, RATE_LIMITS } from '@/lib/rate-limit';

export async function GET(request: NextRequest) {
  try {
    // Auth check
    const authResult = await verifyAdminPermission(request, 'canManageUsers');
    if ('error' in authResult) return authResult.error;

    const users = await db.user.findMany({
      orderBy: { createdAt: 'desc' },
      select: {
        id: true,
        name: true,
        email: true,
        phone: true,
        roles: true,
        isActive: true,
        isVerified: true,
        createdAt: true,
      },
    });

    return NextResponse.json({ success: true, users });
  } catch (error) {
    console.error('Admin users fetch error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to fetch users' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    // Auth + permission check
    const authResult = await verifyAdminPermission(request, 'canManageUsers');
    if ('error' in authResult) return authResult.error;

    // Rate limit
    const identifier = `admin-users-post:${getRateLimitIdentifier(request)}`;
    const rateLimit = checkRateLimit(identifier, RATE_LIMITS.adminWrite);
    if (!rateLimit.allowed) return rateLimitError(rateLimit.resetTime);

    const { name, email, phone, password, roles } = await request.json();

    if (!name || !email || !password) {
      return NextResponse.json(
        { success: false, error: 'Name, email, and password are required' },
        { status: 400 }
      );
    }

    // Validate inputs
    if (!isValidName(name)) {
      return NextResponse.json(
        { success: false, error: 'Name must be between 1 and 100 characters' },
        { status: 400 }
      );
    }

    if (!isValidEmail(email)) {
      return NextResponse.json(
        { success: false, error: 'Invalid email format' },
        { status: 400 }
      );
    }

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

    // Only allow valid roles
    const validRoles = ['general', 'landlord', 'seller', 'houseOwner', 'shopOwner'];
    const userRole = validRoles.includes(roles) ? roles : 'general';

    // Check if user already exists
    const existing = await db.user.findUnique({ where: { email: sanitizeString(email) } });
    if (existing) {
      return NextResponse.json(
        { success: false, error: 'User with this email already exists' },
        { status: 409 }
      );
    }

    // Hash password with base64 (consistent with the app's auth system)
    const hashedPassword = Buffer.from(password).toString('base64');

    const user = await db.user.create({
      data: {
        name: sanitizeString(name),
        email: sanitizeString(email),
        phone: phone ? sanitizeString(phone) : null,
        password: hashedPassword,
        roles: userRole,
        isActive: true,
        isVerified: false,
      },
    });

    return NextResponse.json({ success: true, user: { id: user.id, name: user.name, email: user.email } });
  } catch (error) {
    console.error('Admin user create error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to create user' },
      { status: 500 }
    );
  }
}

export async function PATCH(request: NextRequest) {
  try {
    // Auth + permission check
    const authResult = await verifyAdminPermission(request, 'canManageUsers');
    if ('error' in authResult) return authResult.error;

    const { userId, isActive } = await request.json();

    if (!userId) {
      return NextResponse.json(
        { success: false, error: 'User ID is required' },
        { status: 400 }
      );
    }

    if (!isValidId(userId)) {
      return NextResponse.json(
        { success: false, error: 'Invalid user ID format' },
        { status: 400 }
      );
    }

    if (typeof isActive !== 'boolean') {
      return NextResponse.json(
        { success: false, error: 'isActive must be a boolean' },
        { status: 400 }
      );
    }

    const user = await db.user.update({
      where: { id: userId },
      data: { isActive },
    });

    return NextResponse.json({ success: true, user: { id: user.id, isActive: user.isActive } });
  } catch (error) {
    console.error('Admin user update error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to update user' },
      { status: 500 }
    );
  }
}

export async function DELETE(request: NextRequest) {
  try {
    // Auth + permission check
    const authResult = await verifyAdminPermission(request, 'canManageUsers');
    if ('error' in authResult) return authResult.error;

    const { userId } = await request.json();

    if (!userId) {
      return NextResponse.json(
        { success: false, error: 'User ID is required' },
        { status: 400 }
      );
    }

    if (!isValidId(userId)) {
      return NextResponse.json(
        { success: false, error: 'Invalid user ID format' },
        { status: 400 }
      );
    }

    // Prevent deleting admin users through this endpoint
    const targetUser = await db.user.findUnique({ where: { id: userId }, select: { roles: true } });
    if (targetUser?.roles === 'admin') {
      return NextResponse.json(
        { success: false, error: 'Cannot delete admin users through this endpoint' },
        { status: 403 }
      );
    }

    await db.user.delete({ where: { id: userId } });

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Admin user delete error:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to delete user' },
      { status: 500 }
    );
  }
}
