import { NextRequest } from 'next/server';
import { apiHandler, ok } from '@/lib/utils/api';
import { categoryService } from '@/lib/services/category.service';
import { updateCategorySchema } from '@/lib/validators';
import { requireAdmin, HttpError } from '@/lib/auth/session';

function parseId(raw: string): number {
  const id = Number(raw);
  if (!Number.isInteger(id) || id <= 0) throw new HttpError(400, 'Invalid id');
  return id;
}

export async function PATCH(req: NextRequest, ctx: { params: { id: string } }) {
  return apiHandler(async () => {
    await requireAdmin();
    const id = parseId(ctx.params.id);
    const body = await req.json();
    const input = updateCategorySchema.parse(body);
    const updated = await categoryService.update(id, input);
    return ok(updated);
  });
}

// DELETE deactivates instead of hard deleting, per the planning doc.
// We expose the route as DELETE for REST conventions but the service
// performs a soft delete.
export async function DELETE(_req: NextRequest, ctx: { params: { id: string } }) {
  return apiHandler(async () => {
    await requireAdmin();
    const id = parseId(ctx.params.id);
    const updated = await categoryService.deactivate(id);
    return ok(updated);
  });
}
