import type { APIRoute } from 'astro';
import { getContributionById, updateContribution } from '../../../../lib/db';
import { withinMinutes } from '../../../../lib/markdown';

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 (contribution.user_id !== user.id) {
    return new Response('Forbidden', { status: 403 });
  }
  if (!withinMinutes(contribution.created_at, 10)) {
    return new Response('Edit window closed', { status: 403 });
  }

  return new Response(null, { status: 200 });
};

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

  const contribution = getContributionById(id);
  if (!contribution || contribution.user_id !== user.id || !withinMinutes(contribution.created_at, 10)) {
    return new Response(null, { status: 302, headers: { Location: '/contribute' } });
  }

  return new Response(null, { status: 302, headers: { Location: '/contribute' } });
};
