import { db } from '../database.js'

export const suffixRepository = {
  async create(entry) {
    await db.run('INSERT INTO suffix (user_uuid, user_name, suffix) VALUES (?, ?, ?)', [
      entry.user_uuid,
      entry.user_name,
      entry.suffix,
    ])
  },

  async getByUuid(userUuid) {
    return db.selectOne('SELECT * FROM suffix WHERE user_uuid = ?', [userUuid])
  },

  async getBySuffix(suffix) {
    return db.selectOne('SELECT * FROM suffix WHERE suffix = ?', [suffix])
  },

  async getAll() {
    return db.selectAll('SELECT * FROM suffix ORDER BY user_name')
  },

  async update(userUuid, data) {
    return db.run('UPDATE suffix SET user_name = ?, suffix = ? WHERE user_uuid = ?', [
      data.user_name,
      data.suffix,
      userUuid,
    ])
  },

  async delete(userUuid) {
    return db.run('DELETE FROM suffix WHERE user_uuid = ?', [userUuid])
  },

  /**
   * Renames a suffix across all entity title/label columns.
   * Updates suffix table entry + all titles containing [OLD_SUFFIX] to [NEW_SUFFIX].
   * Runs as a single transaction: a failure (e.g. a UNIQUE-title collision on
   * a renamed title) rolls everything back instead of leaving a half-rename.
   */
  async renameSuffix(userUuid, newSuffix) {
    const existing = await this.getByUuid(userUuid)
    if (!existing) throw new Error('Suffix entry not found')

    const oldPattern = `[${existing.suffix}]`
    const newPattern = `[${newSuffix}]`
    const params = [oldPattern, newPattern, oldPattern]

    await db.batch([
      {
        sql: 'UPDATE suffix SET suffix = ? WHERE user_uuid = ?',
        params: [newSuffix, userUuid],
      },
      {
        sql: "UPDATE exercise SET title = REPLACE(title, ?, ?) WHERE title LIKE '%' || ? || '%'",
        params,
      },
      {
        sql: "UPDATE combo SET title = REPLACE(title, ?, ?) WHERE title LIKE '%' || ? || '%'",
        params,
      },
      {
        sql: "UPDATE session SET title = REPLACE(title, ?, ?) WHERE title LIKE '%' || ? || '%'",
        params,
      },
      {
        sql: "UPDATE collection SET label = REPLACE(label, ?, ?) WHERE label LIKE '%' || ? || '%'",
        params,
      },
    ])
  },
}
