import fs from 'node:fs'
import path from 'node:path'

interface UserMapping {
  conversationId: string
  name: string
  createdAt: string
}

type UserStore = Record<string, UserMapping>

const STORE_PATH = path.join(process.cwd(), 'remote-control', 'data', 'lark-users.json')

function readStore(): UserStore {
  try {
    if (!fs.existsSync(STORE_PATH)) {
      return {}
    }
    const data = fs.readFileSync(STORE_PATH, 'utf-8')
    return JSON.parse(data)
  } catch {
    return {}
  }
}

function writeStore(store: UserStore): void {
  const dir = path.dirname(STORE_PATH)
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true })
  }
  fs.writeFileSync(STORE_PATH, JSON.stringify(store, null, 2), 'utf-8')
}

export function getConversationId(openId: string): string | null {
  const store = readStore()
  return store[openId]?.conversationId ?? null
}

export function setConversationId(openId: string, conversationId: string, name: string): void {
  const store = readStore()
  store[openId] = {
    conversationId,
    name,
    createdAt: new Date().toISOString(),
  }
  writeStore(store)
}
