import { NextRequest, NextResponse } from 'next/server';
import { changePasswordViaService } from '@/lib/platform-client';
import { logError } from '@/lib/logger';

export async function POST(req: NextRequest) {
  try {
    const authHeader = req.headers.get('authorization');
    if (!authHeader) {
      return NextResponse.json({ error: 'Authentication required' }, { status: 401 });
    }
    const token = authHeader.replace('Bearer ', '');

    const { currentPassword, newPassword } = await req.json();
    if (!currentPassword || !newPassword) {
      return NextResponse.json({ error: 'Current and new password required' }, { status: 400 });
    }

    const result = await changePasswordViaService(token, currentPassword, newPassword);
    return NextResponse.json(result);
  } catch (error) {
    const msg = error instanceof Error ? error.message : String(error);
    logError('Change password error', error);
    return NextResponse.json({ error: msg }, { status: 400 });
  }
}
