import { db } from '@/lib/db'
import { NextRequest, NextResponse } from 'next/server'
import { compare } from 'bcryptjs'

// Demo accounts for preview (bypasses database)
const DEMO_ACCOUNTS = [
  {
    id: 'demo-admin-001',
    email: 'admin@isp.com',
    password: 'password123',
    name: 'Super Admin',
    phone: '01711000000',
    username: 'admin',
    role: 'SUPER_ADMIN',
    status: 'ACTIVE',
    address: 'Gulshan, Dhaka',
    areaId: null,
    connectionType: 'FIBER',
  },
  {
    id: 'demo-operator-001',
    email: 'operator@isp.com',
    password: 'password123',
    name: 'System Operator',
    phone: '01812000000',
    username: 'operator',
    role: 'OPERATOR',
    status: 'ACTIVE',
    address: 'Dhanmondi, Dhaka',
    areaId: null,
    connectionType: 'FIBER',
  },
]

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

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

    // Check demo accounts first
    const demoAccount = DEMO_ACCOUNTS.find(
      (a) => a.email === email && a.password === password
    )

    if (demoAccount) {
      const { password: _, ...userWithoutPassword } = demoAccount
      return NextResponse.json({
        success: true,
        data: {
          user: userWithoutPassword,
          token: `demo-${demoAccount.id}-${Date.now()}`,
        },
      })
    }

    // Check database users
    const user = await db.user.findUnique({
      where: { email },
      include: {
        area: true,
        reseller: { select: { id: true, name: true, email: true } },
      },
    })

    if (!user) {
      return NextResponse.json(
        { success: false, error: 'Invalid email or password' },
        { status: 401 }
      )
    }

    // Compare with bcrypt hash
    const isPasswordValid = await compare(password, user.password)

    if (!isPasswordValid) {
      return NextResponse.json(
        { success: false, error: 'Invalid email or password' },
        { status: 401 }
      )
    }

    const { password: _, ...userWithoutPassword } = user

    return NextResponse.json({
      success: true,
      data: {
        user: userWithoutPassword,
        token: user.id,
      },
    })
  } catch (error: unknown) {
    const message = error instanceof Error ? error.message : 'Internal server error'
    return NextResponse.json(
      { success: false, error: message },
      { status: 500 }
    )
  }
}
