import { error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import type { Notification } from '$lib/notif';

let notifications: Notification[] = [
  { id: 1, text: "This is a notification", date: new Date(), status: [] },
  { id: 2, text: "This is another notification", date: new Date(), status: [] },
  { id: 3, text: "This is a third notification", date: new Date(), status: [] },
]

// GET handler
// Returns JSON array of all notifications with "new" in the status dictionary for the current user
// Sets the status of all notifications to "old"

export const GET: RequestHandler = ({ url }) => {
  const { searchParams } = new URL(url);
  const user_id = searchParams.get('id')??"1";
  const date = searchParams.get('date')??"";
  if (!user_id) {
    //return error(400, 'username is required');
  }
  if(!date){
    //return error(400, 'date is required');
  }


  //Notifications that do not have a status entry for the current user and are newer than the date
  const user_notifications = notifications.filter(notification => {
    return notification.status.find(status => status == user_id) == undefined && notification.date > new Date(date);
  });

  //Add the current user to the status list for each notification
  user_notifications.forEach(notification => {
    notification.status.push(user_id);
  });

  return new Response(JSON.stringify(user_notifications), { headers: { 'content-type': 'application/json' } });
};



// POST handler
// Creates a new notification
export const POST: RequestHandler = async ({ request }) => {

  const notification = await request.json();

  notification.id = notifications.length + 1;
  notification.date = new Date();
  notification.status = [];

  notifications = [...notifications, notification];

  return new Response(JSON.stringify(notification), {
    status: 201,
    headers: {
      'Content-Type': 'application/json'
    }
  });

};
