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

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

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

    // Find user
    const user = await prismaAuth.user.findUnique({
      where: { email },
      select: {
        id: true,
        email: true,
        passwordHash: true,
        emailVerified: true,
        isActive: true,
      },
    });

    if (!user) {
      return NextResponse.json(
        { verified: false, exists: false },
        { status: 200 }
      );
    }

    // Check if user is active (treat null/undefined as true)
    if (user.isActive === false) {
      return NextResponse.json(
        { verified: false, exists: true, passwordValid: false, active: false },
        { status: 200 }
      );
    }

    // Check password
    const isPasswordValid = await bcrypt.compare(password, user.passwordHash);

    if (!isPasswordValid) {
      return NextResponse.json(
        { verified: false, exists: true, passwordValid: false },
        { status: 200 }
      );
    }

    // Return verification status
    return NextResponse.json(
      { 
        verified: user.emailVerified,
        exists: true,
        passwordValid: true
      },
      { status: 200 }
    );
  } catch (error: any) {
    console.error('Error checking verification:', error);
    return NextResponse.json(
      { error: 'Failed to check verification status' },
      { status: 500 }
    );
  }
}


