// Site-side mirror of in-game-account → website-user links. The sidecar owns the
// authoritative link (it tags the game account on /link/confirm); this model
// records it locally so the player portal can list links and enforce ownership.

const db = require('./shardLinks.db')

function toSafe(row) {
  if (!row) return null
  return {
    account: row.account,
    userId: row.user_id,
    charName: row.char_name || null,
    linkedAt: row.linked_at,
  }
}

async function link({ account, userId, charName }) {
  return toSafe(await db.upsert({ account, userId, charName }))
}

async function listForUser(userId) {
  const rows = await db.listByUser(userId)
  return rows.map(toSafe)
}

const ownsAccount = (account, userId) => db.isOwnedBy(account, userId)

async function getByAccount(account) {
  return toSafe(await db.getByAccount(account))
}

const unlink = (account, userId) => db.remove(account, userId)

// Drop the local mirror for an account (source-of-truth severed elsewhere).
const removeByAccount = (account) => db.removeByAccount(account)

module.exports = { link, listForUser, ownsAccount, getByAccount, unlink, removeByAccount }
