import { NextResponse } from 'next/server';
import bcrypt from 'bcryptjs';
import connectToDatabase from '@/lib/mongodb';
import AppSettings from '@/models/AppSettings';
import { validateRequest } from '@/lib/auth';

export async function POST(request: Request) {
  try {
    const { valid, error } = validateRequest(request);
    if (!valid) {
      return NextResponse.json({ success: false, error }, { status: 401 });
    }

    await connectToDatabase();
    const { currentPassword, newPassword } = await request.json();

    if (!currentPassword || !newPassword) {
      return NextResponse.json(
        { success: false, error: 'Current and new passwords are required' },
        { status: 400 }
      );
    }

    if (newPassword.length < 4) {
      return NextResponse.json(
        { success: false, error: 'New password must be at least 4 characters' },
        { status: 400 }
      );
    }

    const settings = await AppSettings.findOne();
    if (!settings) {
      return NextResponse.json(
        { success: false, error: 'App settings not found' },
        { status: 404 }
      );
    }

    const isValid = await bcrypt.compare(currentPassword, settings.passwordHash);
    if (!isValid) {
      return NextResponse.json(
        { success: false, error: 'Current password is incorrect' },
        { status: 401 }
      );
    }

    settings.passwordHash = await bcrypt.hash(newPassword, 12);
    await settings.save();

    return NextResponse.json({
      success: true,
      data: { message: 'Password changed successfully' },
    });
  } catch (error: Error | unknown) {
    return NextResponse.json(
      { success: false, error: error instanceof Error ? error.message : 'Failed to change password' },
      { status: 500 }
    );
  }
}
