const { existsSync, readFileSync, writeFileSync } = require('fs');
const path = require('path');

const filePath = path.join(__dirname, 'blacklistedusers.crzy');

function load() {
  if (!existsSync(filePath)) return {};
  const content = readFileSync(filePath, 'utf-8');
  const users = {};
  let current = null;
  for (const raw of content.split('\n')) {
    const line = raw.trim();
    if (!line) continue;
    const section = line.match(/^@user\s+(.+)$/);
    if (section) { current = section[1]; users[current] = { username: '', warnings: 0, blacklisted: false }; continue; }
    if (!current) continue;
    const pair = line.match(/^(\w+)\s*=\s*(.+)$/);
    if (!pair) continue;
    const [, k, v] = pair;
    if (k === 'username') users[current].username = v;
    else if (k === 'warnings') users[current].warnings = parseInt(v);
    else if (k === 'blacklisted') users[current].blacklisted = v === 'true';
  }
  return users;
}

function save(users) {
  const lines = [];
  for (const [id, data] of Object.entries(users)) {
    lines.push(`@user ${id}`, `username = ${data.username}`, `warnings = ${data.warnings}`, `blacklisted = ${data.blacklisted}`, '');
  }
  writeFileSync(filePath, lines.join('\n'));
}

function warn(userId, username) {
  const users = load();
  if (!users[userId]) users[userId] = { username, warnings: 0, blacklisted: false };
  users[userId].username = username;
  users[userId].warnings++;
  if (users[userId].warnings >= 2) users[userId].blacklisted = true;
  save(users);
  return users[userId];
}

function unblacklist(userId) {
  const users = load();
  if (!users[userId]) return null;
  users[userId].warnings = 0;
  users[userId].blacklisted = false;
  save(users);
  return users[userId];
}

function isBlacklisted(userId) {
  const users = load();
  return users[userId]?.blacklisted === true;
}

function getUser(userId) {
  return load()[userId] || null;
}

module.exports = { warn, unblacklist, isBlacklisted, getUser };