import { NextRequest, NextResponse } from 'next/server';

// Mock user database - in production, use a real database
const MOCK_USERS = [
  { id: '1', name: 'Admin User', email: 'admin@fasttimephone.kw', password: 'admin123', role: 'admin' as const, phone: '+96512345678' },
  { id: '2', name: 'Ahmad Al-Rashidi', email: 'ahmad@example.com', password: 'password123', role: 'customer' as const, phone: '+96512345679' },
];

function generateToken(userId: string): string {
  return Buffer.from(JSON.stringify({ userId, exp: Date.now() + 7 * 24 * 60 * 60 * 1000 })).toString('base64');
}

export async function POST(request: NextRequest) {
  try {
    const { email, password } = await request.json();

    const user = MOCK_USERS.find(u => u.email === email && u.password === password);

    if (!user) {
      return NextResponse.json({ success: false, message: 'Invalid credentials' }, { status: 401 });
    }

    const token = generateToken(user.id);
    const { password: _, ...safeUser } = user;

    return NextResponse.json({
      success: true,
      token,
      user: safeUser,
    });
  } catch {
    return NextResponse.json({ success: false, message: 'Server error' }, { status: 500 });
  }
}
