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

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

type UserStore = Record<string, UserMapping>

const STORE_PATH = path.join(process.cwd(), 'remote-control', 'data', 'dingtalk-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(staffId: string): string | null {
  const store = readStore()
  return store[staffId]?.conversationId ?? null
}

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