'use strict';

const TARGET_RE = /^wss?:\/\/[A-Za-z0-9.\-]+(:\d+)?(\/[^\s]*)?$/;
const USERNAME_RE = /^[A-Za-z0-9_]{1,16}$/;

function validateStart(body, cfg) {
  if (!body || typeof body !== 'object') return { ok: false, error: 'Body must be JSON' };
  const { target, bots, usernamePrefix, spawnDelay, botPassword, chatMessages } = body;
  if (typeof target !== 'string' || !TARGET_RE.test(target)) {
    return { ok: false, error: 'Target must be a valid ws:// or wss:// URL' };
  }
  const botCount = parseInt(bots, 10);
  if (isNaN(botCount) || botCount < 1 || botCount > cfg.bots.max_bots) {
    return { ok: false, error: `Bots must be 1..${cfg.bots.max_bots}` };
  }
  if (usernamePrefix !== undefined) {
    if (typeof usernamePrefix !== 'string' || !USERNAME_RE.test(usernamePrefix)) {
      return { ok: false, error: 'Username prefix must be 1-16 chars [A-Za-z0-9_]' };
    }
  }
  if (spawnDelay !== undefined) {
    const d = parseInt(spawnDelay, 10);
    if (isNaN(d) || d < 0 || d > cfg.bots.max_spawn_delay) {
      return { ok: false, error: `Spawn delay must be 0..${cfg.bots.max_spawn_delay}` };
    }
  }
  if (botPassword !== undefined) {
    if (typeof botPassword !== 'string' || botPassword.length < 1 || botPassword.length > 64) {
      return { ok: false, error: 'Bot password must be 1..64 chars' };
    }
  }
  if (chatMessages !== undefined) {
    let arr;
    if (typeof chatMessages === 'string') {
      arr = chatMessages.split('\n').map(l => l.trim()).filter(Boolean);
    } else if (Array.isArray(chatMessages)) {
      arr = chatMessages;
    } else {
      return { ok: false, error: 'chatMessages must be a string or array' };
    }
    if (arr.length > 50) return { ok: false, error: 'Max 50 chat messages' };
    for (const m of arr) {
      if (typeof m !== 'string' || m.length === 0 || m.length > 256) {
        return { ok: false, error: 'Each chat message must be 1..256 chars' };
      }
    }
  }
  return { ok: true };
}

function validateProxyUpload(text) {
  if (typeof text !== 'string' || !text.trim()) {
    return { ok: false, error: 'Need proxies text' };
  }
  const lines = text.split('\n').filter(l => l.trim());
  if (lines.length > 5000) return { ok: false, error: 'Max 5000 lines per upload' };
  if (text.length > 5 * 1024 * 1024) return { ok: false, error: 'Payload too large' };
  return { ok: true };
}

module.exports = { validateStart, validateProxyUpload, TARGET_RE, USERNAME_RE };
