import { NextResponse } from 'next/server';
import { z } from 'zod';

import { auth } from '@/lib/auth';
import { withAuth } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { createAuditLog } from '@/lib/audit';
import { errorResponse, ValidationError } from '@/lib/errors';

const bodySchema = z.object({
  currentPassword: z.string().min(1, 'Current password is required'),
  newPassword: z.string().min(9, 'Password must be at least 9 characters'),
  revokeOtherSessions: z.boolean().optional(),
});

export const POST = withAuth(async (req, ctx) => {
  try {
    const body = await parseBody(req, bodySchema);
    const result = await auth.api.changePassword({
      body: {
        currentPassword: body.currentPassword,
        newPassword: body.newPassword,
        revokeOtherSessions: body.revokeOtherSessions,
      },
      headers: req.headers,
    });

    void createAuditLog({
      portId: ctx.portId || null,
      userId: ctx.userId,
      action: 'password_change',
      entityType: 'user',
      entityId: ctx.userId,
      metadata: {
        revokedOtherSessions: !!body.revokeOtherSessions,
      },
      ipAddress: ctx.ipAddress,
      userAgent: ctx.userAgent,
    });

    return NextResponse.json({ data: { ok: true, user: result.user } });
  } catch (err) {
    if (err && typeof err === 'object' && 'message' in err) {
      const msg = String((err as { message?: unknown }).message ?? '');
      if (
        msg.toLowerCase().includes('invalid password') ||
        msg.toLowerCase().includes('incorrect')
      ) {
        return errorResponse(new ValidationError('Current password is incorrect'));
      }
    }
    return errorResponse(err);
  }
});
