import { NextResponse } from 'next/server';
import db from '@/lib/db';
import { getAdminSession, hashPassword } from '@/lib/auth';

// PUT /api/admin/settings/profile — update admin profile
export async function PUT(request: Request) {
  const session = await getAdminSession();
  if (!session) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  try {
    const body = await request.json();
    const { username, currentPassword, newPassword } = body;

    // Update username
    if (username) {
      const sanitizedUsername = String(username).trim().slice(0, 100);
      await db.execute(
        'UPDATE admins SET username = ? WHERE email = ?',
        [sanitizedUsername, session.email]
      );
    }

    // Change password
    if (currentPassword && newPassword) {
      const adminRows = await db.query(
        'SELECT password_hash FROM admins WHERE email = ?',
        [session.email]
      ) as any[];

      if (!adminRows || adminRows.length === 0) {
        return NextResponse.json({ error: 'Admin not found' }, { status: 404 });
      }

      const { comparePassword } = await import('@/lib/auth');
      const isValid = await comparePassword(currentPassword, adminRows[0].password_hash);
      if (!isValid) {
        return NextResponse.json({ error: 'Current password is incorrect' }, { status: 400 });
      }

      if (newPassword.length < 6) {
        return NextResponse.json({ error: 'New password must be at least 6 characters' }, { status: 400 });
      }

      const newHash = await hashPassword(newPassword);
      await db.execute(
        'UPDATE admins SET password_hash = ? WHERE email = ?',
        [newHash, session.email]
      );
    }

    return NextResponse.json({ success: true });
  } catch (error: any) {
    console.error('[Settings Profile API] Error:', error.message);
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
