import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import {
  loadDimcodeUserCache,
  loadDimcodeUserConfig,
  saveDimcodeUserConfig,
} from '../src/dimsdk/compat/archships/dim-agent/config/user-store.ts'

const tempHomes: string[] = []

afterEach(() => {
  while (tempHomes.length > 0) {
    rmSync(tempHomes.pop() as string, { force: true, recursive: true })
  }
})

describe('user store helpers', () => {
  it('round-trips saved config through the dimcode config dir', async () => {
    const home = mkdtempSync(`${tmpdir()}/best-agent-user-store-`)
    tempHomes.push(home)
    const env = { HOME: home }
    const filePath = join(home, '.dimcode', 'config.json')

    await saveDimcodeUserConfig(filePath, {
      version: 1,
      updatedAt: 7,
      settings: {
        providerId: 'openai',
      },
    })

    const loaded = await loadDimcodeUserConfig(env)

    expect(loaded.filePath).toBe(filePath)
    expect(loaded.config).toEqual({
      version: 1,
      updatedAt: 7,
      settings: {
        providerId: 'openai',
      },
    })
  })

  it('falls back to empty defaults when cache/config files are not version 1', async () => {
    const home = mkdtempSync(`${tmpdir()}/best-agent-user-store-invalid-`)
    tempHomes.push(home)
    const env = { HOME: home }
    mkdirSync(join(home, '.dimcode', 'dimcode'), { recursive: true })
    writeFileSync(
      join(home, '.dimcode', 'dimcode', 'cache.json'),
      JSON.stringify({ version: 2, updatedAt: 99 }),
      'utf8',
    )
    writeFileSync(
      join(home, '.dimcode', 'config.json'),
      JSON.stringify({ version: 0, updatedAt: 88 }),
      'utf8',
    )

    const [cache, config] = await Promise.all([
      loadDimcodeUserCache(env),
      loadDimcodeUserConfig(env),
    ])

    expect(cache.cache).toEqual({ version: 1, updatedAt: 0 })
    expect(config.config).toEqual({ version: 1, updatedAt: 0 })
  })
})
