// API client — same-origin fetch wrapper for the ASP.NET Core backend

const API = (() => {
  function getToken() { return localStorage.getItem('moment_token'); }
  function setToken(t) { localStorage.setItem('moment_token', t); }
  function clearToken() { localStorage.removeItem('moment_token'); }

  async function req(method, path, body, isForm) {
    const headers = {};
    const token = getToken();
    if (token) headers['Authorization'] = `Bearer ${token}`;
    if (body && !isForm) headers['Content-Type'] = 'application/json';

    const res = await fetch(path, {
      method,
      headers,
      body: body ? (isForm ? body : JSON.stringify(body)) : undefined,
    });

    if (!res.ok) {
      const ct = res.headers.get('content-type') || '';
      const err = ct.includes('application/json')
        ? await res.json().catch(() => ({}))
        : {};
      const fallbackMessage =
        res.status === 401 ? '아이디 또는 비밀번호를 확인해주세요.' :
        res.status === 404 ? '가입된 회원 정보가 없습니다. 회원가입 후 로그인해주세요.' :
        res.status >= 500 ? '서버에서 문제가 발생했습니다. 잠시 후 다시 시도해주세요.' :
        `요청을 처리하지 못했습니다 (${res.status})`;
      const e = new Error(err.message || fallbackMessage);
      e.status = res.status;
      throw e;
    }

    const ct = res.headers.get('content-type') || '';
    if (ct.includes('application/json')) return res.json();
    return null;
  }

  return {
    getToken, setToken, clearToken,

    // Auth
    login: (username, password) =>
      req('POST', '/api/auth/login', { username, password }),
    register: (username, password, name) =>
      req('POST', '/api/auth/register', { username, password, name }),
    me: () => req('GET', '/api/me'),

    // Groups
    getGroups: () => req('GET', '/api/groups'),
    createGroup: (name, capacity, isPublic) =>
      req('POST', '/api/groups', { name, capacity, isPublic }),
    joinGroup: (inviteCode, groupId) =>
      req('POST', '/api/groups/join', { inviteCode, groupId }),
    getGroup: (id) => req('GET', `/api/groups/${id}`),
    getPublicGroups: (query) =>
      req('GET', `/api/groups/public?query=${encodeURIComponent(query || '')}`),

    // Dashboard & uploads
    getDashboard: (groupId) => req('GET', `/api/groups/${groupId}/dashboard`),
    reactToUpload: (groupId, uploadUserId, reactionType) =>
      req('POST', `/api/groups/${groupId}/uploads/${uploadUserId}/reaction`, { reactionType }),
    upload: (groupId, file, caption) => {
      const form = new FormData();
      form.append('file', file);
      form.append('caption', caption || '');
      return req('POST', `/api/groups/${groupId}/uploads`, form, true);
    },

    // Archive
    getArchiveCalendar: (groupId, year, month) =>
      req('GET', `/api/groups/${groupId}/archive/calendar?year=${year}&month=${month}`),
    getArchive: (groupId) => req('GET', `/api/groups/${groupId}/archive`),
    getArchiveDetail: (groupId, date) =>
      req('GET', `/api/groups/${groupId}/archive/${date}`),

    // Reminders & questions
    getReminders: () => req('GET', '/api/reminders/today'),
    getTodayQuestion: () => req('GET', '/api/questions/today'),

    // Template votes
    getTemplateVotes: (groupId) =>
      req('GET', `/api/groups/${groupId}/template-votes`),
    voteTemplate: (groupId, templateId) =>
      req('POST', `/api/groups/${groupId}/template-votes`, { templateId }),
    generateCollage: (groupId, templateId, force = false) =>
      req('POST', `/api/groups/${groupId}/collage/generate`, { templateId, force }),
  };
})();

window.API = API;
