import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';
import { eq } from 'drizzle-orm';

import { db } from '@/lib/db';
import { portalUsers } from '@/lib/db/schema/portal';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse, UnauthorizedError } from '@/lib/errors';
import { getPortalSession } from '@/lib/portal/auth';
import { changePortalPassword } from '@/lib/services/portal-auth.service';

const bodySchema = z.object({
  currentPassword: z.string().min(1),
  newPassword: z.string().min(9),
});

export async function POST(req: NextRequest): Promise<NextResponse> {
  try {
    const session = await getPortalSession();
    if (!session) throw new UnauthorizedError('Portal session required');

    const { currentPassword, newPassword } = await parseBody(req, bodySchema);

    const user = await db.query.portalUsers.findFirst({
      where: eq(portalUsers.email, session.email),
    });
    if (!user) throw new UnauthorizedError('Portal account not found');

    await changePortalPassword({
      portalUserId: user.id,
      currentPassword,
      newPassword,
    });

    return NextResponse.json({ data: { ok: true } });
  } catch (error) {
    return errorResponse(error);
  }
}
