/* Admin — Supabase-backed content CRUD */

async function fetchContents(filter) {
  let q = window.supabaseClient.from('contents').select('*').order('created_at', { ascending: false });
  if (filter && filter.type) q = q.eq('type', filter.type);
  const { data, error } = await q;
  if (error) { console.error(error); return []; }
  return data;
}

async function insertContent(row) {
  const { data, error } = await window.supabaseClient.from('contents').insert(row).select().single();
  if (error) { console.error(error); return null; }
  return data;
}

async function deleteContent(id) {
  const { error } = await window.supabaseClient.from('contents').delete().eq('id', id);
  if (error) console.error(error);
  return !error;
}

async function fetchContentById(id) {
  const { data, error } = await window.supabaseClient.from('contents').select('*').eq('id', id).single();
  if (error) { console.error(error); return null; }
  return data;
}

async function updateContentTitle(id, title) {
  const { error } = await window.supabaseClient.from('contents').update({ title }).eq('id', id);
  if (error) { console.error(error); return false; }
  return true;
}

async function updateContentTopic(id, topic) {
  const { error } = await window.supabaseClient.from('contents').update({ topic }).eq('id', id);
  if (error) { console.error(error); return false; }
  return true;
}

/* downloads: file upload to the public "downloads" storage bucket
   (storage keys must be ASCII, so Korean kind labels are mapped to a slug) */

const DOWNLOAD_KIND_SLUGS = { 가이드북: 'guidebook', 월간: 'monthly', 주간: 'weekly', 일간: 'daily' };

async function uploadDownloadFile(kind, file) {
  const ext = (file.name.split('.').pop() || 'pdf').toLowerCase().replace(/[^a-z0-9]/g, '') || 'pdf';
  const slug = DOWNLOAD_KIND_SLUGS[kind] || 'file';
  const path = slug + '-' + Date.now() + '-' + Math.random().toString(36).slice(2) + '.' + ext;
  const { error } = await window.supabaseClient.storage.from('downloads').upload(path, file, { upsert: true, contentType: file.type });
  if (error) { console.error(error); return null; }
  const { data } = window.supabaseClient.storage.from('downloads').getPublicUrl(path);
  return { url: data.publicUrl, label: file.name };
}

/* downloads: full-replace save (delete existing rows for this content, insert the non-empty ones) */

async function saveContentDownloads(contentId, downloads) {
  const del = await window.supabaseClient.from('content_downloads').delete().eq('content_id', contentId);
  if (del.error) { console.error(del.error); return false; }
  const rows = downloads
    .filter((d) => d.file_url.trim())
    .map((d) => ({ content_id: contentId, kind: d.kind, file_url: d.file_url.trim(), file_label: d.file_label.trim() }));
  if (!rows.length) return true;
  const { error } = await window.supabaseClient.from('content_downloads').insert(rows);
  if (error) { console.error(error); return false; }
  return true;
}

/* weekly curriculum writes (수업지원자료 전용: 4주 x 2활동 + 3차시) */

async function insertWeeklyPlan(contentId, weeklyPlan) {
  const activityRows = [];
  const chapterRows = [];
  weeklyPlan.forEach((w, wi) => {
    const hasContent = w.activities.some((a) => a.title.trim()) || w.chapters.some((c) => c.title.trim());
    if (!hasContent) return;
    const week = wi + 1;
    w.activities.forEach((a, slot) => {
      activityRows.push({ content_id: contentId, week, slot, who: slot === 0 ? '모모' : '테리', badge: a.badge, title: a.title, sub: a.sub });
    });
    w.chapters.forEach((c, slot) => {
      chapterRows.push({ content_id: contentId, week, slot, no: c.no, title: c.title, sub: c.sub, time: c.time });
    });
  });
  if (!activityRows.length && !chapterRows.length) return true;
  const [r1, r2] = await Promise.all([
    window.supabaseClient.from('content_week_activities').insert(activityRows),
    window.supabaseClient.from('content_week_chapters').insert(chapterRows),
  ]);
  if (r1.error) console.error(r1.error);
  if (r2.error) console.error(r2.error);
  return !r1.error && !r2.error;
}

/* 확장수업(가정 연계) writes — 3 family cards + 3 recommended videos, tied to the same 수업지원자료 content row */

async function insertFamilyExtras(contentId, familyItems, videos) {
  const hasFamily = familyItems.some((f) => f.title.trim());
  const hasVideos = videos.some((v) => v.title.trim());
  const familyRows = hasFamily
    ? familyItems.map((f, slot) => ({ content_id: contentId, slot, label: f.label, title: f.title.replace(/\\n/g, '\n'), kind: f.kind, vol: f.vol, sub: f.sub, pastel: slot }))
    : [];
  const videoRows = hasVideos
    ? videos.map((v, slot) => ({ content_id: contentId, slot, title: v.title, tag: v.tag, sub: v.sub, pastel: slot }))
    : [];
  if (!familyRows.length && !videoRows.length) return true;
  const [r1, r2] = await Promise.all([
    familyRows.length ? window.supabaseClient.from('content_family_items').insert(familyRows) : Promise.resolve({ error: null }),
    videoRows.length ? window.supabaseClient.from('content_videos').insert(videoRows) : Promise.resolve({ error: null }),
  ]);
  if (r1.error) console.error(r1.error);
  if (r2.error) console.error(r2.error);
  return !r1.error && !r2.error;
}

/* member (site login) management — routed through an edge function so the
   service-role key never reaches the browser */

const MANAGE_MEMBERS_URL = 'https://iqlflfiruurohmvuagnx.supabase.co/functions/v1/manage-members';

async function callManageMembers(body) {
  const { data: sess } = await window.supabaseClient.auth.getSession();
  const token = sess.session && sess.session.access_token;
  const res = await fetch(MANAGE_MEMBERS_URL, {
    method: 'POST',
    headers: { 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  });
  const json = await res.json();
  if (!res.ok) throw new Error(json.error || 'request failed');
  return json;
}

async function listMembers() {
  try {
    const { members } = await callManageMembers({ action: 'list' });
    return members;
  } catch (e) { console.error(e); return []; }
}

async function createMember(profile) {
  try {
    const { member } = await callManageMembers({ action: 'create', ...profile });
    return member;
  } catch (e) { console.error(e); return null; }
}

async function updateMember(id, profile) {
  try {
    await callManageMembers({ action: 'update', id, ...profile });
    return true;
  } catch (e) { console.error(e); return false; }
}

async function deleteMember(id) {
  try {
    await callManageMembers({ action: 'delete', id });
    return true;
  } catch (e) { console.error(e); return false; }
}

Object.assign(window, { fetchContents, insertContent, deleteContent, fetchContentById, updateContentTitle, updateContentTopic, saveContentDownloads, uploadDownloadFile, insertWeeklyPlan, insertFamilyExtras, listMembers, createMember, updateMember, deleteMember });
