import {
  format,
} from 'npm:date-fns@4.1.0';

export interface FahrzeugplanungItemDto {
  _id?: string;
  className: string;      // 'greenItem' OR 'blocked'
  group: string;          // Fahrzeug ID
  mitarbeiterId: string;  // Mitarbeiter ID
  start: string;          // ISO 8601 TS (UTC)
  end: string;            // ISO 8601 TS (UTC)
}

function chunk<T>(input: T[], size: number): T[][] {
  return input.reduce(
    (array, item, index) =>
      index % size === 0
        ? [...array, [item]]
        : [...array.slice(0, -1), [...array.slice(-1)[0], item]],
    [] as T[][]
  );
}

function sleep(ms: number) {
  return new Promise(resolve => setTimeout(resolve, ms))
}

async function deleteSchichtplanungItems(ids: string[]) {
  const endpoint = 'custom/open-api/fahrzeugplanung/delete';
  const url = `https://avicenna.dispolive.de/${endpoint}`;

  console.log(`Deleting ids: ${ids.join(', ')}`)
  return await Promise.all(
    ids.map(id => fetch(`${url}/${id}`, {
      method: "GET",
      headers: {
        Authorization: `Bearer ba397e8a-29f2-4c99-9141-75a71fd55830`,
        'dispolive-api-version': 'v1.0.1',
      },
    }))
  );
}

async function getSchichtplanungForDay(day: Date) {
  const endpoint = 'custom/open-api/fahrzeugplanung/findByRange';
  const url = `https://avicenna.dispolive.de/${endpoint}/${format(new Date(day), 'yyyy-MM-dd')}_${format(new Date(day), 'yyyy-MM-dd')}`;

  return await fetch(url, {
    method: "GET",
    headers: {
      Authorization: `Bearer ba397e8a-29f2-4c99-9141-75a71fd55830`,
      'dispolive-api-version': 'v1.0.1',
    },
  });
}

async function main() {
  const schichtplanung = await getSchichtplanungForDay(new Date('2025-08-11')).then(response => response.json());
  const chunks = chunk(schichtplanung.map(({id}) => id), 1)
  for(const chunk of chunks) {
    const res = await deleteSchichtplanungItems(chunk as string[])
    console.log(res)
    await sleep(200)
  }
}

await main()