import { hasTable } from './db.js';

async function hasColumn(pool, tableName, columnName) {
  const [rows] = await pool.query(
    'SELECT COUNT(*) AS c FROM information_schema.columns WHERE table_schema = DATABASE() AND table_name = ? AND column_name = ?',
    [tableName, columnName]
  );
  return (rows?.[0]?.c ?? 0) > 0;
}

export async function initMySqlSupport(pool) {
  return {
    hasMatchTicks: await hasTable(pool, 'match_ticks'),
    matchesHasDiscipline: await hasColumn(pool, 'matches', 'Discipline'),
    matchesHasParticipants: await hasColumn(pool, 'matches', 'Participants'),
    matchesHasRate: await hasColumn(pool, 'matches', 'Rate'),
    matchesHasScore: await hasColumn(pool, 'matches', 'Score'),
  };
}

export async function createMatchRow(pool, support, { team1Id, team2Id, startTimeUtc, platform, matchType, participantsJson, discipline }) {
  const columns = ['Team1_ID', 'Team2_ID', 'StartTime', 'Status', 'Platform', 'MatchType'];
  const values = [team1Id, team2Id, startTimeUtc, 'live', platform, matchType];

  if (support.matchesHasScore) {
    columns.push('Score');
    values.push('0:0');
  }

  if (support.matchesHasRate) {
    columns.push('Rate');
    values.push('free');
  }

  if (support.matchesHasParticipants) {
    columns.push('Participants');
    values.push(participantsJson);
  }

  if (discipline && support.matchesHasDiscipline) {
    columns.push('Discipline');
    values.push(discipline);
  }

  const placeholders = columns.map(() => '?').join(', ');
  const sql = `INSERT INTO matches (${columns.join(', ')}) VALUES (${placeholders})`;
  try {
    const [result] = await pool.execute(sql, values);
    return Number(result.insertId);
  } catch {
    const fallbackColumns = ['Team1_ID', 'Team2_ID', 'StartTime', 'Status', 'Platform', 'MatchType'];
    const fallbackValues = [team1Id, team2Id, startTimeUtc, 'live', platform, matchType];

    if (support.matchesHasScore) {
      fallbackColumns.push('Score');
      fallbackValues.push('0:0');
    }

    const fallbackSql = `INSERT INTO matches (${fallbackColumns.join(', ')}) VALUES (${fallbackColumns.map(() => '?').join(', ')})`;
    const [result] = await pool.execute(fallbackSql, fallbackValues);
    return Number(result.insertId);
  }
}

export async function updateMatchPerSecond(pool, support, matchId, { status, score, participantsJson }) {
  const set = ['Status = ?', 'Score = ?'];
  const params = [status, score];

  if (support.matchesHasParticipants) {
    set.push('Participants = ?');
    params.push(participantsJson);
  }

  const sql = `UPDATE matches SET ${set.join(', ')} WHERE ID = ?`;
  params.push(matchId);
  await pool.execute(sql, params);
}

export async function endMatch(pool, matchId, { score, endTimeUtc }) {
  const sql = `UPDATE matches SET Status = 'end', Score = ?, EndTime = ? WHERE ID = ?`;
  await pool.execute(sql, [score, endTimeUtc, matchId]);
}

export async function insertMatchTick(pool, matchId, tickTsUtc, stateJson) {
  const sql = `INSERT INTO match_ticks (match_id, tick_time, state_json) VALUES (?, ?, ?)`;
  await pool.execute(sql, [matchId, tickTsUtc, stateJson]);
}
