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: [{ username: "user1", status: "new" }, { username: "user2", status: "new" }] },
  { id: 2, text: "This is another notification", date: new Date(), status: [{ username: "user1", status: "new" }, { username: "user2", status: "new" }] },
  { id: 3, text: "This is a third notification", date: new Date(), status: [{ username: "user1", status: "new" }, { username: "user2", status: "new" }] },
]

// 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 username = searchParams.get('username');
  if (!username) {
    return error(400, 'username is required');
  }
  const user_notifications = notifications.filter(notification => {
    // return true;
    const user_status = notification.status.find(status => status.username === username);
    if (user_status?.status === "new") {
      console.log("found one!")
      user_status.status = "old";
      //@ts-ignore
      // notifications.find(n => notification.id === n.id).status.find(status => status.username === username).status = "old";
      return true;
    }
    return false;
  });
  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 = [{ username: "user1", status: "new" }, { username: "user2", status: "new" }];

  notifications = [...notifications, notification];

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

};
