/**
 * Integration tests for clear() — fully clears storage, including across a restart.
 *
 * Rewritten for 8.0: the original v5.10.4 suite asserted copy-on-write internals
 * (`_cow/` directory + a `cow-disabled` marker). COW was removed in 8.0 (replaced by
 * generational MVCC), so those internals no longer exist. These tests verify the
 * durable BEHAVIOR that the original bug report cared about: `clear()` empties the
 * store, and a fresh instance opened over the same path sees no data.
 *
 * NO MOCKS — real filesystem + memory storage. Every brain is closed in teardown so
 * background flush / writer-lock heartbeat timers cannot bleed across tests.
 */

import { describe, it, expect, afterEach } from 'vitest'
import { Brainy } from '../../src/brainy.js'
import * as fs from 'fs'

describe('clear() fully clears storage', () => {
  const testStoragePath = './test-clear-persistence-' + Date.now()
  const brains: Brainy[] = []

  const open = async (rootDirectory = testStoragePath): Promise<Brainy> => {
    const brain = new Brainy({
      requireSubtype: false,
      storage: { type: 'filesystem', path: rootDirectory }
    })
    await brain.init()
    brains.push(brain)
    return brain
  }

  afterEach(async () => {
    for (const b of brains.splice(0)) {
      try {
        await b.close()
      } catch {
        /* already closed */
      }
    }
    for (const p of [testStoragePath, testStoragePath + '-multi']) {
      try {
        if (fs.existsSync(p)) await fs.promises.rm(p, { recursive: true, force: true })
      } catch {
        /* ignore cleanup errors */
      }
    }
  })

  it('fully clears persistent storage, including after a restart (the reported scenario)', async () => {
    const brain1 = await open()
    await brain1.add({ data: 'Test Entity', type: 'concept' })
    expect((await brain1.find({ type: 'concept' })).length).toBe(1)

    await brain1.clear()
    expect((await brain1.find({ type: 'concept' })).length).toBe(0)
    await brain1.close()

    // New instance over the same path — data must NOT come back.
    const brain2 = await open()
    expect((await brain2.find({ type: 'concept' })).length).toBe(0)
  })

  it('clears both entities and relations across a restart', async () => {
    const brain1 = await open()
    const e1 = await brain1.add({ data: 'Entity 1', type: 'person' })
    const e2 = await brain1.add({ data: 'Entity 2', type: 'concept' })
    await brain1.relate({ from: e1, to: e2, type: 'relatedTo' })
    expect((await brain1.find({ type: 'person' })).length).toBe(1)
    expect((await brain1.related({})).length).toBe(1)

    await brain1.clear()
    await brain1.close()

    const brain2 = await open()
    expect((await brain2.find({ type: 'person' })).length).toBe(0)
    expect((await brain2.find({ type: 'concept' })).length).toBe(0)
    expect((await brain2.related({})).length).toBe(0)
  })

  it('works across multiple clear() cycles and restarts', async () => {
    const p = testStoragePath + '-multi'
    const brain1 = await open(p)
    await brain1.add({ data: 'Entity 1', type: 'concept' })
    expect((await brain1.find({ type: 'concept' })).length).toBe(1)
    await brain1.clear()
    await brain1.close()

    const brain2 = await open(p)
    expect((await brain2.find({ type: 'concept' })).length).toBe(0)
    await brain2.add({ data: 'Entity 2', type: 'concept' })
    expect((await brain2.find({ type: 'concept' })).length).toBe(1)
    await brain2.clear()
    await brain2.close()

    const brain3 = await open(p)
    expect((await brain3.find({ type: 'concept' })).length).toBe(0)
  })

  it('handles clear() on empty storage', async () => {
    const brain = await open()
    await expect(brain.clear()).resolves.not.toThrow()
    expect((await brain.find({ type: 'concept' })).length).toBe(0)
  })
})

describe('clear() works for memory storage', () => {
  it('clears memory storage completely', async () => {
    const brain = new Brainy({ requireSubtype: false, storage: { type: 'memory' } })
    await brain.init()
    try {
      await brain.add({ data: 'Test', type: 'concept' })
      expect((await brain.find({ type: 'concept' })).length).toBe(1)
      await brain.clear()
      expect((await brain.find({ type: 'concept' })).length).toBe(0)
    } finally {
      await brain.close()
    }
  })
})
