import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { mkdtemp, readFile, rm, writeFile } from 'fs/promises'
import os from 'os'
import path from 'path'

let tempDir: string
let cwdSpy: ReturnType<typeof vi.spyOn>

async function importFreshService() {
  vi.resetModules()
  return import('./platformContentService')
}

describe('platformContentService', () => {
  beforeEach(async () => {
    tempDir = await mkdtemp(path.join(os.tmpdir(), 'rdg-platform-content-'))
    await import('fs/promises').then((fs) => fs.mkdir(path.join(tempDir, 'apps/api'), { recursive: true }))
    cwdSpy = vi.spyOn(process, 'cwd').mockReturnValue(path.join(tempDir, 'apps/api'))
  })

  afterEach(async () => {
    cwdSpy.mockRestore()
    await rm(tempDir, { recursive: true, force: true })
    vi.resetModules()
  })

  it('returns cloned default homepage content when the file does not exist or cannot be parsed', async () => {
    const service = await importFreshService()

    const first = await service.getCarplaceHomepageContent()
    first.en.heroTitle = 'Mutated by test'

    const second = await service.getCarplaceHomepageContent()
    expect(second.en.sections).toContain('hero')
    expect(second.en.heroTitle).not.toBe('Mutated by test')
  })

  it('saves only the Carplace homepage field while preserving unrelated platform content fields', async () => {
    const dataPath = path.join(tempDir, 'apps/api/src/data/platform-content.json')
    await writeFile(dataPath, JSON.stringify({ otherSetting: { keep: true } }), 'utf8').catch(async () => {
      await import('fs/promises').then((fs) => fs.mkdir(path.dirname(dataPath), { recursive: true }))
      await writeFile(dataPath, JSON.stringify({ otherSetting: { keep: true } }), 'utf8')
    })

    const service = await importFreshService()
    const homepage = await service.getCarplaceHomepageContent()
    homepage.en.heroTitle = 'A better Carplace title'

    await expect(service.saveCarplaceHomepageContent(homepage)).resolves.toBe(homepage)

    const raw = JSON.parse(await readFile(dataPath, 'utf8'))
    expect(raw.otherSetting).toEqual({ keep: true })
    expect(raw.carplaceHomepage.en.heroTitle).toBe('A better Carplace title')
  })
})
