import { mkdir, readFile, writeFile } from 'fs/promises'
import path from 'path'
import { cloneStorefrontHomepageContent, type StorefrontHomepageConfig } 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 = {
  storefrontHomepage?: StorefrontHomepageConfig
}

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 getStorefrontHomepageContent() {
  const content = await readPlatformContentFile()
  return content.storefrontHomepage ?? cloneStorefrontHomepageContent()
}

export async function saveStorefrontHomepageContent(homepage: StorefrontHomepageConfig) {
  const content = await readPlatformContentFile()
  await writePlatformContentFile({
    ...content,
    storefrontHomepage: homepage,
  })
  return homepage
}
