import type { APIRoute } from 'astro';
import { addReaction, removeReaction, hasReaction, getContributionById } from '../../../../lib/db';

export const POST: APIRoute = ({ locals, params, request }) => {
  const user = locals.user;
  const id = Number(params.id);

  if (!id || isNaN(id)) {
    return new Response('Not found', { status: 404 });
  }

  const contribution = getContributionById(id);
  if (!contribution || contribution.hidden_at) {
    return new Response('Not found', { status: 404 });
  }

  if (hasReaction(user.id, id)) {
    removeReaction(user.id, id);
  } else {
    addReaction(user.id, id);
  }

  const referer = request.headers.get('referer') ?? '/contribute';
  return new Response(null, {
    status: 302,
    headers: { Location: `${referer}#c-${id}` },
  });
};
