import { db } from "./db"; const supabaseUrl = import.meta.env.VITE_SUPABASE_URL; const supabaseAnonKey = import.meta.env.VITE_SUPABASE_ANON_KEY; // 테이블 조회·쓰기는 서버 함수(api/db.js)를 거친다 (src/lib/db.ts). 브라우저에는 테이블 권한이 없다. // 아래 주소와 공개 키는 Edge Function 호출(fnHeaders)에만 쓴다. /** Common headers for Edge Function calls (includes JWT auth) */ const fnHeaders = () => ({ "Content-Type": "application/json", "Authorization": `Bearer ${supabaseAnonKey}`, }); export async function generateMarketingReport(url: string, clinicName?: string) { const response = await fetch( `${supabaseUrl}/functions/v1/generate-report`, { method: "POST", headers: fnHeaders(), body: JSON.stringify({ url, clinicName }), } ); if (!response.ok) { throw new Error(`Report generation failed: ${response.statusText}`); } return response.json(); } export async function fetchReportById(reportId: string) { // 예전 Supabase 클라이언트처럼 행 형태를 호출하는 쪽이 정한다. const { data, error } = await db("report.byId", { id: reportId }); if (error) throw new Error(`Failed to fetch report: ${error.message}`); return data; } /** * Fetch pipeline status for a report. * Used by AnalysisLoadingPage to resume interrupted pipelines. */ export interface PipelineStatus { reportId: string; clinicId?: string; runId?: string; status: string; clinicName?: string; hasChannelData: boolean; hasReport: boolean; } export async function fetchPipelineStatus(reportId: string): Promise { const { data, error } = await db<{ id: string; status: string | null; clinic_name?: string; channel_data: Record | null; report: Record | null; }>("report.status", { id: reportId }); if (error || !data) throw new Error(`Report not found: ${error?.message}`); return { reportId: data.id, status: data.status || "unknown", clinicName: data.clinic_name, hasChannelData: !!data.channel_data && Object.keys(data.channel_data).length > 0, hasReport: !!data.report && Object.keys(data.report).length > 0, }; } export interface EnrichChannelsRequest { reportId: string; clinicName: string; instagramHandle?: string; instagramHandles?: string[]; youtubeChannelId?: string; facebookHandle?: string; address?: string; } /** * Fire-and-forget: triggers background channel enrichment. * Returns enrichment result when the Edge Function completes (~27s). */ export async function enrichChannels(params: EnrichChannelsRequest) { const response = await fetch( `${supabaseUrl}/functions/v1/enrich-channels`, { method: "POST", headers: fnHeaders(), body: JSON.stringify(params), } ); if (!response.ok) { throw new Error(`Channel enrichment failed: ${response.statusText}`); } return response.json(); } export async function scrapeWebsite(url: string, clinicName?: string) { const response = await fetch( `${supabaseUrl}/functions/v1/scrape-website`, { method: "POST", headers: fnHeaders(), body: JSON.stringify({ url, clinicName }), } ); if (!response.ok) { throw new Error(`Scraping failed: ${response.statusText}`); } return response.json(); } // ─── Pipeline V2 API Functions ─── /** * 사용자가 직접 붙여넣은 채널 URL 묶음. * 전달 시 Edge Function이 해당 플랫폼의 Firecrawl discovery를 스킵하고 * 제공된 URL을 `verified_channels`에 직접 주입합니다. */ export interface ManualChannels { youtube?: string[]; instagram?: string[]; facebook?: string[]; naverPlace?: string[]; naverBlog?: string[]; gangnamUnni?: string[]; } /** * Phase 1: Discover & verify social channels from website URL. * Returns verified handles + reportId for subsequent phases. * * @param url 병원 홈페이지 URL (필수). * @param clinicName 병원명 (선택) — 수동 입력 또는 clinic_registry 매칭용. * @param manualChannels (선택) 사용자가 직접 붙여넣은 채널 URL. 존재하는 플랫폼은 * Firecrawl discovery를 스킵하고 사용자 제공 값을 우선 사용합니다. */ export async function discoverChannels( url: string, clinicName?: string, manualChannels?: ManualChannels, ) { const response = await fetch( `${supabaseUrl}/functions/v1/discover-channels`, { method: "POST", headers: fnHeaders(), body: JSON.stringify({ url, clinicName, manualChannels }), } ); const data = await response.json(); if (!response.ok) { const err = new Error(data.error || `Channel discovery failed: ${response.statusText}`); (err as Error & { code?: string; domain?: string }).code = data.error; (err as Error & { code?: string; domain?: string }).domain = data.domain; throw err; } return data; } /** * Phase 2: Collect all channel data using verified handles. * Reads verified_channels from DB, runs parallel API calls. */ export async function collectChannelData(reportId: string, clinicId?: string, runId?: string) { const response = await fetch( `${supabaseUrl}/functions/v1/collect-channel-data`, { method: "POST", headers: fnHeaders(), body: JSON.stringify({ reportId, clinicId, runId }), } ); if (!response.ok) { throw new Error(`Data collection failed: ${response.statusText}`); } return response.json(); } /** * Phase 3: Generate AI report using real collected data from DB. */ export async function generateReportV2(reportId: string, clinicId?: string, runId?: string) { const response = await fetch( `${supabaseUrl}/functions/v1/generate-report`, { method: "POST", headers: fnHeaders(), body: JSON.stringify({ reportId, clinicId, runId }), } ); if (!response.ok) { throw new Error(`Report generation failed: ${response.statusText}`); } return response.json(); } // ─── Pipeline V2 Phase 4: Content Plan ─── /** * Phase 4: Generate AI content strategy and calendar. * Reads report data from DB, calls Perplexity for strategy generation, * stores result in content_plans table. */ export async function generateContentPlan(reportId: string, clinicId?: string, runId?: string) { const response = await fetch( `${supabaseUrl}/functions/v1/generate-content-plan`, { method: "POST", headers: fnHeaders(), body: JSON.stringify({ reportId, clinicId, runId }), } ); if (!response.ok) { throw new Error(`Content plan generation failed: ${response.statusText}`); } return response.json(); } /** * Fetch the active content plan for a clinic. * Returns the most recent is_active=true plan with all JSONB columns. */ export async function fetchActiveContentPlan(clinicId: string) { const { data, error } = await db("plan.active", { clinicId }); if (error) return null; return data; } /** * Update a single calendar entry within a content plan's JSONB. * Uses Postgres JSONB path update. */ export async function updateCalendarEntry( planId: string, entryId: string, updates: Record, ) { // 읽기·수정·저장을 서버 함수가 한 번에 한다. const { error: writeErr } = await db("plan.updateEntry", { planId, entryId, updates }); if (writeErr) throw new Error(`Update failed: ${writeErr.message}`); } /** * Trigger strategy adjustment for a clinic. * Compares current vs previous channel_snapshots, generates AI recommendations. */ export async function triggerStrategyAdjustment(clinicId: string) { const response = await fetch( `${supabaseUrl}/functions/v1/adjust-strategy`, { method: "POST", headers: fnHeaders(), body: JSON.stringify({ clinicId }), } ); if (!response.ok) { throw new Error(`Strategy adjustment failed: ${response.statusText}`); } return response.json(); }