'use server';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { setCountdown } from '~/server/functions';
import { middleware } from '~/middleware';
import type { Countdown } from '~/server/types';

export const POST = async (request: NextRequest) => {
  const middlewareResponse = await middleware(request);
  if (middlewareResponse) return middlewareResponse;
  try { 
    const body = await request.json() as {
      userId: number;
      countdown: Countdown;
    };
    const { userId, countdown } = body;
    if (!userId || !countdown || isNaN(userId))
      return NextResponse.json(
        { message: 'Missing userId or countdown' }, { status: 400 }
      );
    const newCountdown: Countdown = await setCountdown(userId, countdown);
    if (!newCountdown) {
      return NextResponse.json(
        { message: 'Error setting countdown' }, { status: 500 }
      );
    }
    return NextResponse.json(newCountdown);
  } catch (error) {
    console.error('Error setting countdown:', error);
    if (error instanceof Error) {
      return NextResponse.json(
        { message: error.message }, { status: 500 }
      );
    } else {
      return NextResponse.json(
        { message: 'Unknown error occurred' }, { status: 500 }
      );
    }
  }
};
