import { NextResponse } from 'next/server';
import { db } from '../../../../db';
import { users } from '../../../../drizzle/schema';
import bcrypt from 'bcryptjs';
import { eq } from 'drizzle-orm';

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

    // Fetch the user from the database
    const user = await db.select()
      .from(users)
      .where(eq(users.email, email))
      .limit(1)
      .then(rows => rows[0]);

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

    // Compare the provided password with the stored hashed password
    const isPasswordValid = await bcrypt.compare(password, user.passwordHash);

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

    // If authentication is successful, you can set a session or token here
    // For example, using JWT or setting a session cookie

    return NextResponse.json({ message: 'Sign in successful', redirect: '/Armory' }, { status: 200 });
  } catch (error) {
    console.error('Sign in error:', error);
    return NextResponse.json({ error: 'Failed to sign in' }, { status: 500 });
  }
} 