import { NextRequest, NextResponse } from 'next/server';
import { db, schema } from '@/lib/db';
import { getSession } from '@/lib/auth';
import { eq, and } from 'drizzle-orm';
import bcrypt from 'bcrypt';
import { passwordChangeSchema } from '@/lib/validators';

// PUT - Change password
export async function PUT(request: NextRequest) {
  try {
    const accessToken = request.cookies.get('scriba.access_token')?.value;
    const session = await getSession(accessToken);

    if (!session) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const body = await request.json();
    const parsed = passwordChangeSchema.safeParse(body);
    if (!parsed.success) {
      return NextResponse.json({ error: parsed.error.issues[0]?.message ?? 'Input non valido' }, { status: 400 });
    }
    const { currentPassword, newPassword } = parsed.data;

    // Get user's credential account
    const account = await db.query.accounts.findFirst({
      where: and(
        eq(schema.accounts.userId, session.user.id),
        eq(schema.accounts.providerId, 'credential')
      )
    });

    if (!account || !account.password) {
      return NextResponse.json({ error: 'No password set for this account' }, { status: 400 });
    }

    // Verify current password
    const isValid = await bcrypt.compare(currentPassword, account.password);
    if (!isValid) {
      return NextResponse.json({ error: 'Current password is incorrect' }, { status: 401 });
    }

    // Hash new password
    const hashedPassword = await bcrypt.hash(newPassword, 10);

    // Update password
    await db.update(schema.accounts)
      .set({ password: hashedPassword, updatedAt: new Date() })
      .where(eq(schema.accounts.id, account.id));

    return NextResponse.json({ success: true, message: 'Password updated successfully' });
  } catch (error) {
    console.error('Password change error:', error);
    return NextResponse.json({ error: 'Failed to change password' }, { status: 500 });
  }
}
