// PublicEventService.js
// 모든 public API 호출을 담당하는 서비스 (토큰 자동 관리)

const STORAGE_KEY = 'event_token_';

function getToken(publicHash) {
  return sessionStorage.getItem(STORAGE_KEY + publicHash);
}
function setToken(publicHash, token) {
  sessionStorage.setItem(STORAGE_KEY + publicHash, token);
}
function removeToken(publicHash) {
  sessionStorage.removeItem(STORAGE_KEY + publicHash);
}

async function fetchEvent(publicHash, password) {
  let token = getToken(publicHash);
  const headers = { 'Content-Type': 'application/json' };
  if (token) headers['Authorization'] = 'Bearer ' + token;
  let body = undefined;
  if (!token && password) {
    body = JSON.stringify({ password });
  }

  const res = await fetch(`/api/public/${publicHash}`, {
    method: 'POST',
    headers,
    body
  });
  if (res.status === 403 || res.status === 401 || res.status === 404) {
    removeToken(publicHash);
  }
  const data = await res.json();
  if (data.token) {
    setToken(publicHash, data.token);
  }
  return { status: res.status, data };
}

async function updateScore(publicHash, participantId, gameNumber, score, handicap, teamNumber = null) {
  let token = getToken(publicHash);
  const headers = { 'Content-Type': 'application/json' };
  if (token) headers['Authorization'] = 'Bearer ' + token;
  const res = await fetch(`/api/public/${publicHash}/score`, {
    method: 'PUT',
    headers,
    body: JSON.stringify({ participantId, gameNumber, score, handicap, teamNumber })
  });
  return res;
}

async function registerParticipant(publicHash, payload) {
  let token = getToken(publicHash);
  const headers = { 'Content-Type': 'application/json' };
  if (token) headers['Authorization'] = 'Bearer ' + token;
  const res = await fetch(`/api/public/${publicHash}/participant`, {
    method: 'POST',
    headers,
    body: JSON.stringify(payload)
  });
  return res;
}

async function createGuest(publicHash, payload) {
  let token = getToken(publicHash);
  const headers = { 'Content-Type': 'application/json' };
  if (token) headers['Authorization'] = 'Bearer ' + token;
  const res = await fetch(`/api/public/${publicHash}/guest`, {
    method: 'POST',
    headers,
    body: JSON.stringify(payload)
  });
  return await res.json();
}

export default {
  fetchEvent,
  updateScore,
  registerParticipant,
  createGuest,
  getToken,
  setToken,
  removeToken
};
