/**
 * Thin wrapper around the PES League Laravel API (bot endpoints).
 * All requests use  Authorization: Bot <BOT_SECRET>
 */

import fetch from 'node-fetch';

const BASE  = process.env.API_URL?.replace(/\/$/, '');
const SECRET = process.env.BOT_SECRET;

if (!BASE)   throw new Error('API_URL is not set in .env');
if (!SECRET) throw new Error('BOT_SECRET is not set in .env');

const headers = {
    'Content-Type': 'application/json',
    'Accept':        'application/json',
    'Authorization': `Bot ${SECRET}`,
};

async function request(method, path, body = null) {
    const url = `${BASE}/bot${path}`;
    const opts = { method, headers };
    if (body) opts.body = JSON.stringify(body);

    const res = await fetch(url, opts);
    const json = await res.json().catch(() => ({}));

    if (!res.ok) {
        const msg = json?.error ?? json?.message ?? `HTTP ${res.status}`;
        throw new Error(msg);
    }
    return json;
}

// ── Ranked matches ────────────────────────────────────────────────────────────

/** List pending / in_progress ranked matches */
export function getPendingMatches() {
    return request('GET', '/pending-matches');
}

/**
 * Admin-submit final score for a ranked match.
 * @param {number} matchId
 * @param {number} scoreHost
 * @param {number} scoreGuest
 */
export function submitMatchScore(matchId, scoreHost, scoreGuest) {
    return request('POST', '/match-score', {
        match_id:    matchId,
        score_host:  scoreHost,
        score_guest: scoreGuest,
    });
}

// ── Tournament matches ────────────────────────────────────────────────────────

/** List active tournaments */
export function getTournaments() {
    return request('GET', '/tournaments');
}

/**
 * List pending tournament matches for a specific tournament.
 * @param {number} tournamentId
 */
export function getTournamentPendingMatches(tournamentId) {
    return request('GET', `/tournament/${tournamentId}/pending-matches`);
}

/**
 * Submit score for a tournament match.
 * @param {number} tournamentMatchId
 * @param {number} score1
 * @param {number} score2
 */
export function submitTournamentScore(tournamentMatchId, score1, score2) {
    return request('POST', '/tournament-score', {
        tournament_match_id: tournamentMatchId,
        score1,
        score2,
    });
}

// ── Player lookup ─────────────────────────────────────────────────────────────

/**
 * Look up a player by Discord ID.
 * @param {string} discordId
 */
export function findPlayerByDiscordId(discordId) {
    return request('GET', `/player?discord_id=${encodeURIComponent(discordId)}`);
}

/**
 * Look up a player by in-game username.
 * @param {string} username
 */
export function findPlayerByUsername(username) {
    return request('GET', `/player?username=${encodeURIComponent(username)}`);
}
