import supa from '@/components/supadb/aksupainstance.uts'

export type InsightDetail = {
  id: string
  report_id: string
  type: string
  impact: string
  title: string
  content: string
  created_at: string
}

export type RelatedReport = {
  id: string
  title: string
  type: string
  period: string
  generated_at: string
}

export async function fetchInsightDetail(insightId: string): Promise<InsightDetail | null> {
  const res: any = await supa
    .from('analytics_insights')
    .select('id, report_id, type, impact, title, content, created_at')
    .eq('id', insightId)
    .single()

  if (res?.error != null) {
    throw res.error
  }

  const it: any = res.data
  if (it == null) return null

  return {
    id: `${it.id}`,
    report_id: `${it.report_id || ''}`,
    type: `${it.type || 'info'}`,
    impact: `${it.impact || 'medium'}`,
    title: `${it.title || ''}`,
    content: `${it.content || ''}`,
    created_at: `${it.created_at || ''}`
  }
}

export async function fetchRelatedReport(reportId: string): Promise<RelatedReport | null> {
  const rRes: any = await supa
    .from('analytics_reports')
    .select('id, title, type, period, generated_at')
    .eq('id', reportId)
    .single()

  if (rRes?.error != null) {
    throw rRes.error
  }

  const r: any = rRes.data
  if (r == null) return null

  return {
    id: `${r.id}`,
    title: `${r.title}`,
    type: `${r.type}`,
    period: `${r.period}`,
    generated_at: `${r.generated_at || ''}`
  }
}
