const NOTION_VERSION = '2022-06-28'

function getHeaders() {
  const token = process.env.PAI_NOTION_TOKEN
  if (!token) throw new Error('PAI_NOTION_TOKEN not set')
  return {
    Authorization: `Bearer ${token}`,
    'Notion-Version': NOTION_VERSION,
    'Content-Type': 'application/json',
  }
}

export const DBS: Record<string, string> = {
  'GSO Gruppencoaching': '3641a317-e544-81f0-aa71-dc214949b532',
  'OWV': '3641a317-e544-8105-84e8-d1bbcf6940a6',
  'OSD': '3641a317-e544-8102-b677-ec4a77266d1c',
  'Womenmatic': '3641a317-e544-8163-a10f-f2aa2669b2c6',
  'Olga Izieva': '3641a317-e544-81ea-8f53-e21d20afda3f',
  'Tecnoclean': '3641a317-e544-8113-a047-cb227d16d5ac',
  'Dennis Alter': '3641a317-e544-810f-8a4c-e628e1d636fb',
  'Interessenten': '3641a317-e544-8144-a67c-f39dab33b49c',
  'MC Intern': '3661a317-e544-8187-b7f2-f5c899f09d85',
  'Urlaub Kroatien': '3641a317-e544-819b-b28b-e6a49cf54dcb',
  'Alltags ToDos': '3641a317-e544-812e-af33-e1912fe95416',
}

export interface Todo {
  id: string
  name: string
  projekt: string
  status: string | null
  prioritaet: string | null
  deadline: string | null
  startdatum: string | null
  geplanterTag: string | null
  meilenstein: string | null
  zeitH: number | null
  tatsaechlicheZeitH: number | null
  zeitdifferenzH: number | null
  kategorie: string | null
  imWochenplan: boolean
}

async function fetchDbPages(dbId: string): Promise<any[]> {
  const headers = getHeaders()
  const pages: any[] = []
  let cursor: string | undefined

  while (true) {
    const body: Record<string, unknown> = { page_size: 100 }
    if (cursor) body.start_cursor = cursor

    const res = await fetch(`https://api.notion.com/v1/databases/${dbId}/query`, {
      method: 'POST',
      headers,
      body: JSON.stringify(body),
      next: { revalidate: 300 },
    })

    if (!res.ok) break
    const data = await res.json()
    pages.push(...(data.results ?? []))
    if (!data.has_more) break
    cursor = data.next_cursor
  }

  return pages
}

function parseTodo(page: any, projektName: string): Todo {
  const p = page.properties ?? {}

  const name = (p['Name']?.title ?? [])
    .map((t: any) => t.plain_text as string)
    .join('')

  const zeitH = p['Zeit (h)']?.number ?? null
  const tatsaechlicheZeitH = p['Tatsächliche Zeit (h)']?.number ?? null
  const zdRaw = p['Zeitdifferenz (h)']?.formula
  const zeitdifferenzH =
    zdRaw?.type === 'number' ? (zdRaw.number ?? null) : null

  return {
    id: page.id,
    name,
    projekt: projektName,
    status: p['Status']?.status?.name ?? null,
    prioritaet: p['Priorität']?.select?.name ?? null,
    deadline: p['Deadline']?.date?.start ?? null,
    startdatum: p['Startdatum']?.date?.start ?? null,
    geplanterTag: p['Geplanter Tag']?.date?.start ?? null,
    meilenstein: p['Meilenstein']?.select?.name ?? null,
    zeitH,
    tatsaechlicheZeitH,
    zeitdifferenzH,
    kategorie: p['Kategorie']?.select?.name ?? null,
    imWochenplan: p['Im Wochenplan']?.checkbox ?? false,
  }
}

export async function fetchAllTodos(): Promise<Todo[]> {
  const results = await Promise.all(
    Object.entries(DBS).map(async ([name, id]) => {
      const pages = await fetchDbPages(id)
      return pages.map((p) => parseTodo(p, name))
    })
  )
  return results.flat()
}
