import { mkdir, readFile, writeFile } from 'fs/promises'
import path from 'path'
import {
  cloneCarplaceHomepageContent,
  type CarplaceHomepageConfig,
} from '@rentaldrivego/types'

function resolveContentPath() {
  const cwd = process.cwd()
  const appScoped = path.resolve(cwd, 'src/data/platform-content.json')
  const repoScoped = path.resolve(cwd, 'apps/api/src/data/platform-content.json')
  return cwd.includes('/apps/api') ? appScoped : repoScoped
}

const platformContentPath = resolveContentPath()

type PlatformContentFile = {
  carplaceHomepage?: CarplaceHomepageConfig
}

async function readPlatformContentFile(): Promise<PlatformContentFile> {
  try {
    const raw = await readFile(platformContentPath, 'utf8')
    return JSON.parse(raw) as PlatformContentFile
  } catch {
    return {}
  }
}

async function writePlatformContentFile(content: PlatformContentFile) {
  await mkdir(path.dirname(platformContentPath), { recursive: true })
  await writeFile(platformContentPath, JSON.stringify(content, null, 2))
}

export async function getCarplaceHomepageContent() {
  const content = await readPlatformContentFile()
  return content.carplaceHomepage ?? cloneCarplaceHomepageContent()
}

export async function saveCarplaceHomepageContent(homepage: CarplaceHomepageConfig) {
  const content = await readPlatformContentFile()
  await writePlatformContentFile({
    ...content,
    carplaceHomepage: homepage,
  })
  return homepage
}
