// Mark an answer as the best answer. Service enforces the rule that
// only the question owner or an admin can do this.

import { NextRequest } from 'next/server';
import { apiHandler, ok } from '@/lib/utils/api';
import { questionService } from '@/lib/services/question.service';
import { requireAuth, HttpError } from '@/lib/auth/session';
import { z } from 'zod';

const bodySchema = z.object({ answerId: z.number().int().positive() });

export async function POST(req: NextRequest, ctx: { params: { id: string } }) {
  return apiHandler(async () => {
    const user = await requireAuth();
    const questionId = Number(ctx.params.id);
    if (!Number.isInteger(questionId) || questionId <= 0) {
      throw new HttpError(400, 'Invalid question id');
    }
    const { answerId } = bodySchema.parse(await req.json());
    const updated = await questionService.markBestAnswer({
      questionId,
      answerId,
      actorId: user.userId,
      actorRole: user.role,
    });
    return ok(updated);
  });
}
