import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'

import {
  confirmRoutine,
  cancelRoutineConfirmation,
  setChildRoutineOverride,
  setChildOverride,
} from '../api'

describe('routine api helpers', () => {
  const originalFetch = globalThis.fetch

  beforeEach(() => {
    globalThis.fetch = vi.fn().mockResolvedValue({ ok: true, status: 200 } as Response)
  })

  afterEach(() => {
    globalThis.fetch = originalFetch
  })

  it('confirmRoutine posts to confirm endpoint', async () => {
    await confirmRoutine('child-1', 'routine-1')

    expect(globalThis.fetch).toHaveBeenCalledWith('/api/child/child-1/confirm-routine', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ routine_id: 'routine-1' }),
    })
  })

  it('cancelRoutineConfirmation posts to cancel endpoint', async () => {
    await cancelRoutineConfirmation('child-2', 'routine-2')

    expect(globalThis.fetch).toHaveBeenCalledWith('/api/child/child-2/cancel-routine-confirmation', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ routine_id: 'routine-2' }),
    })
  })

  it('setChildRoutineOverride delegates to override endpoint with routine entity type', async () => {
    await setChildRoutineOverride('child-3', 'routine-3', 11)

    expect(globalThis.fetch).toHaveBeenCalledWith('/api/child/child-3/override', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ entity_id: 'routine-3', entity_type: 'routine', custom_value: 11 }),
    })
  })

  it('setChildOverride supports routine entity type directly', async () => {
    await setChildOverride('child-4', 'routine-4', 'routine', 12)

    expect(globalThis.fetch).toHaveBeenCalledWith('/api/child/child-4/override', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ entity_id: 'routine-4', entity_type: 'routine', custom_value: 12 }),
    })
  })
})
