в данном коде проблема связанная с изменением и удалением задачи . import { gapi } from 'gapi-script';
import { Todo } from '../redux/tasks/types';
import { isEqual } from 'date-fns';

const calendarID = import.meta.env.VITE_GOOGLE_CALENDAR_ID;
const apiKey = import.meta.env.VITE_GOOGLE_CALENDAR_API_KEY;
const scope = 'https://www.googleapis.com/auth/calendar.events';
// export const addEventGoogleCalendar = (task: Todo) => {
//   if (task.reminder != '') {
//     const event = {
//       summary: task.title,
//       start: {
//         dateTime: new Date(task.reminder),
//         timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
//       },
//       end: {
//         dateTime: new Date(new Date(task.reminder).getTime() + 60 * 60 * 1000),
//         timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
//       },
//       // повторяющееся событие recurrence: ['RRULE:FREQ=DAILY;COUNT=2'],
//       // Параметр attendees используется для добавления участников в событие: [],
//       reminders: {
//         useDefault: false,
//         overrides: [
//           // { method: 'email', minutes: 24 * 60 },
//           { method: 'popup', minutes: 0 },
//         ],
//       },
//     };

//     function getAccessToken() {
//       gapi.load('client:auth2', () => {
//         gapi.client.init({
//           apiKey: apiKey,
//           clientId: calendarID,
//           discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest'],
//           scope: 'https://www.googleapis.com/auth/calendar.events',
//         });
//         gapi.auth2
//           .getAuthInstance()
//           .signIn()
//           .then(() => {
//             const accessToken = gapi.auth2
//               .getAuthInstance()
//               .currentUser.get()
//               .getAuthResponse().access_token;
//             localStorage.setItem('access_token', accessToken);
//             addPostGoggleCalendar();
//             return accessToken;
//           });
//       });
//     }

//     const addPostGoggleCalendar = () => {
//       const tokenStorage = localStorage.getItem('access_token');

//       function initiate() {
//         gapi.client
//           .request({
//             path: `https://www.googleapis.com/calendar/v3/calendars/primary/events`,
//             method: 'POST',
//             body: event,
//             headers: {
//               'Content-type': 'application/json',
//               Authorization: `Bearer ${tokenStorage}`,
//             },
//           })
//           .then((response: any) => {
//             return [true, response];
//           })
//           .catch((err: any) => {
//             if (err.status === 401) {
//               getAccessToken();
//             }
//             console.log(err);
//             return [false, err];
//           });
//       }
//       gapi.load('client', initiate);
//     };
//     addPostGoggleCalendar();
//   }
// };

// accessToken.js
function getAccessToken(): Promise<string> {
  return new Promise<string>((resolve, reject) => {
    const tokenStorage = localStorage.getItem('access_token');
    const expiryTime = localStorage.getItem('expiry_time');
    const now = new Date().getTime();

    if (tokenStorage && expiryTime && now < Number(expiryTime)) {
      // Токен действителен, просто верните его
      resolve(tokenStorage);
    } else {
      // Если токена нет или он недействителен, начните процесс авторизации
      gapi.load('client:auth2', () => {
        gapi.client
          .init({
            apiKey: apiKey,
            clientId: calendarID,
            discoveryDocs: ['https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest'],
            scope: scope,
          })
          .then(() => {
            gapi.auth2
              .getAuthInstance()
              .signIn()
              .then(() => {
                const authResponse = gapi.auth2
                  .getAuthInstance()
                  .currentUser.get()
                  .getAuthResponse();
                const accessToken = authResponse.access_token;
                const expiryTime = authResponse.expires_at;
                localStorage.setItem('access_token', accessToken);
                localStorage.setItem('expiry_time', expiryTime.toString());
                resolve(accessToken);
              });
          })
          .catch((err) => {
            reject(err);
          });
      });
    }
  });
}

export const addEventGoogleCalendar = async (task: Todo) => {
  const addPostGoggleCalendar = () => {
    const tokenStorage = localStorage.getItem('access_token');
    const event = {
      summary: task.title,
      start: {
        dateTime: new Date(task.reminder),
        timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
      },
      end: {
        dateTime: new Date(new Date(task.reminder).getTime() + 60 * 60 * 1000),
        timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
      },
      reminders: {
        useDefault: false,
        overrides: [{ method: 'popup', minutes: 0 }],
      },
    };

    return new Promise((resolve, reject) => {
      let attemptCount = 0;
      function initiate() {
        gapi.client
          .request({
            path: `https://www.googleapis.com/calendar/v3/calendars/primary/events`,
            method: 'POST',
            body: event,
            headers: {
              'Content-type': 'application/json',
              Authorization: `Bearer ${tokenStorage}`,
            },
          })
          .then((response: any) => {
            resolve([true, response]);
          })
          .catch((err: any) => {
            if (err.status === 401 && attemptCount < 3) {
              // Ограничьте количество попыток до 3
              attemptCount++;
              getAccessToken()
                .then(() => {
                  initiate();
                })
                .catch((err) => {
                  console.log(err);
                  reject([false, err]);
                });
            } else {
              console.log(err);
              reject([false, err]);
            }
          });
      }
      gapi.load('client', initiate);
    });
  };

  try {
    await getAccessToken();
    await addPostGoggleCalendar();
  } catch (error) {
    console.log(error);
  }
};

export const deleteEventGoogleCalendar = async (task: Todo) => {
  const removeEvent = async (events: any) => {
    const tokenStorage = localStorage.getItem('access_token');

    const eventId: string = events.filter((event: any) => {
      const dateCalendar = new Date(event.start.dateTime);
      const dateTask = new Date(task.reminder);
      if (isEqual(dateCalendar, dateTask)) {
        return event.summary === task.title && event.id !== undefined;
      }
    })[0]?.id;

    return new Promise((resolve, reject) => {
      let attemptCount = 0;
      function initiate() {
        gapi.client
          .request({
            path: `https://www.googleapis.com/calendar/v3/calendars/primary/events/${eventId}`,
            method: 'DELETE',
            headers: {
              'Content-type': 'application/json',
              Authorization: `Bearer ${tokenStorage}`,
            },
          })
          .then((response: any) => {
            resolve([true, response]);
          })
          .catch((err: any) => {
            if (err.status === 401 && attemptCount < 3) {
              // Ограничьте количество попыток до 3
              attemptCount++;
              getAccessToken()
                .then(() => {
                  initiate();
                })
                .catch((err) => {
                  console.log(err);
                  reject([false, err]);
                });
            } else {
              console.log(err);
              reject([false, err]);
            }
          });
      }
      gapi.load('client', initiate);
    });
  };

  const getEvents = () => {
    const tokenStorage = localStorage.getItem('access_token');

    return new Promise((resolve, reject) => {
      let attemptCount = 0;
      function initiate() {
        gapi.client
          .init({
            apiKey: apiKey,
          })
          .then(function () {
            return gapi.client.request({
              path: `https://www.googleapis.com/calendar/v3/calendars/primary/events`,
              headers: {
                'Content-type': 'application/json',
                Authorization: `Bearer ${tokenStorage}`,
              },
            });
          })
          .then((response: any) => {
            let events = response.result.items;
            resolve(events);
          })
          .catch((err: any) => {
            if (err.status === 401 && attemptCount < 3) {
              // Ограничьте количество попыток до 3
              attemptCount++;
              getAccessToken()
                .then(() => {
                  initiate();
                })
                .catch((err) => {
                  console.log(err);
                  reject([false, err]);
                });
            } else {
              console.log(err);
              reject([false, err]);
            }
          });
      }
      gapi.load('client', initiate);
    });
  }; в консоль выводит ошибку googleCalendar.ts:234 
{result: {…}, body: '{\n "error": {\n  "errors": [\n   {\n    "domain": "gl… ],\n  "code": 404,\n  "message": "Not Found"\n }\n}\n', headers: {…}, status: 404, statusText: null}
body
: 
"{\n \"error\": {\n  \"errors\": [\n   {\n    \"domain\": \"global\",\n    \"reason\": \"notFound\",\n    \"message\": \"Not Found\"\n   }\n  ],\n  \"code\": 404,\n  \"message\": \"Not Found\"\n }\n}\n"
headers
: 
{cache-control: 'no-cache, no-store, max-age=0, must-revalidate', content-encoding: 'gzip', content-length: '120', content-type: 'application/json; charset=UTF-8', date: 'Mon, 19 Aug 2024 04:37:12 GMT', …}
result
: 
{error: {…}}
status
: 
404
statusText
: 
null
[[Prototype]]
: 
Object 

  try {
    await getAccessToken();
    const events = await getEvents();
    await removeEvent(events);
  } catch (error) {
    console.log(error);
  }
};
googleCalendar.ts:293 
(2) [false, {…}]
0
: 
false
1
: 
{result: {…}, body: '{\n "error": {\n  "errors": [\n   {\n    "domain": "gl… ],\n  "code": 404,\n  "message": "Not Found"\n }\n}\n', headers: {…}, status: 404, statusText: null}
length
: 
2
[[Prototype]]
: 
Array(0)