/**
 * WhatsApp admin tools (legacy CI `whatsapp/*`).
 * Expected Laravel routes under `/api/v1/whatsapp`.
 */
import { apiFetch } from './http'

const BASE = '/api/v1/whatsapp'

function unwrapData<T>(body: T | { data?: T }): T {
  if (body && typeof body === 'object' && 'data' in body && (body as { data?: T }).data != null) {
    return (body as { data?: T }).data as T
  }
  return body as T
}

export type WhatsappSectionRow = {
  class_section_id?: number
  id?: number
  class_section_name?: string
  name?: string
  school_year?: string
  semester?: string
}

export type WhatsappLinkRow = {
  id?: number
  class_section_id?: number
  class_section_name?: string
  invite_link?: string | null
  active?: number | boolean
}

export type WhatsappManageLinksResponse = {
  schoolYear?: string | null
  semester?: string | null
  sections?: WhatsappSectionRow[]
  linksBySection?: Record<string, WhatsappLinkRow>
  parents?: Array<{
    id: number
    firstname?: string | null
    lastname?: string | null
    email?: string | null
    source?: string | null
  }>
}

export type ParentContactRow = {
  firstname?: string | null
  lastname?: string | null
  type?: string | null
  phone?: string | null
  email?: string | null
}

export type WhatsappParentContactsResponse = {
  schoolYear?: string | null
  semester?: string | null
  contacts?: ParentContactRow[]
}

export type ParentContactsByClassParentRow = {
  class_section_id?: number
  primary_id?: number
  primary_name?: string
  primary_phone?: string | null
  primary_member?: string | null
  second_id?: number
  second_name?: string
  second_phone?: string | null
  second_member?: string | null
}

export type ParentContactsByClassSection = {
  class_section_id?: number
  class_section_name?: string
  school_year?: string
  semester?: string
  parents?: ParentContactsByClassParentRow[]
}

export type WhatsappParentContactsByClassResponse = {
  classSections?: ParentContactsByClassSection[]
}

export async function fetchWhatsappManageLinks(params?: {
  school_year?: string
  semester?: string
}): Promise<WhatsappManageLinksResponse> {
  const qs = new URLSearchParams()
  if (params?.school_year) qs.set('school_year', params.school_year)
  if (params?.semester) qs.set('semester', params.semester)
  if (!qs.has('per_page')) qs.set('per_page', '200')
  const suffix = qs.toString() ? `?${qs}` : ''
  const body = await apiFetch<WhatsappManageLinksResponse & {
    data?: WhatsappManageLinksResponse & { links?: WhatsappLinkRow[] }
    links?: WhatsappLinkRow[]
    class_sections?: ParentContactsByClassSection[]
  }>(`${BASE}/links${suffix}`)
  const data = unwrapData(body) as WhatsappManageLinksResponse & {
    links?: WhatsappLinkRow[]
    class_sections?: ParentContactsByClassSection[]
  }

  if (!data.sections && data.class_sections) data.sections = data.class_sections

  if (!data.linksBySection && Array.isArray(data.links)) {
    data.linksBySection = Object.fromEntries(
      data.links
        .filter((link) => link.class_section_id != null)
        .map((link) => [String(link.class_section_id), link]),
    )
  }

  return data
}

export async function saveWhatsappLink(payload: {
  class_section_id: number
  class_section_name?: string
  invite_link: string
  active?: boolean
}): Promise<{ ok?: boolean; message?: string }> {
  return unwrapData(await apiFetch(`${BASE}/links`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  }))
}

export async function sendWhatsappInvites(payload: {
  mode: 'all' | 'class' | 'parents'
  class_section_id?: number | null
  parent_ids?: number[]
}): Promise<{ ok?: boolean; message?: string }> {
  return unwrapData(await apiFetch(`${BASE}/invites/send`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  }))
}

export async function fetchWhatsappParentContacts(params?: {
  school_year?: string
  semester?: string
}): Promise<WhatsappParentContactsResponse> {
  const qs = new URLSearchParams()
  if (params?.school_year) qs.set('school_year', params.school_year)
  if (params?.semester) qs.set('semester', params.semester)
  const suffix = qs.toString() ? `?${qs}` : ''
  const body = await apiFetch<WhatsappParentContactsResponse & { data?: WhatsappParentContactsResponse }>(`${BASE}/parent-contacts${suffix}`)
  return unwrapData(body)
}

export async function fetchWhatsappParentContactsByClass(params?: {
  school_year?: string
  semester?: string
}): Promise<WhatsappParentContactsByClassResponse> {
  const qs = new URLSearchParams()
  if (params?.school_year) qs.set('school_year', params.school_year)
  if (params?.semester) qs.set('semester', params.semester)
  const suffix = qs.toString() ? `?${qs}` : ''
  const body = await apiFetch<{
    data?: { class_sections?: ParentContactsByClassSection[]; classSections?: ParentContactsByClassSection[] }
    class_sections?: ParentContactsByClassSection[]
    classSections?: ParentContactsByClassSection[]
  }>(`${BASE}/parent-contacts-by-class${suffix}`)
  const data = unwrapData(body)
  return { classSections: data.classSections ?? data.class_sections ?? [] }
}

export async function updateWhatsappMembership(payload: {
  class_section_id: number
  school_year?: string
  semester?: string
  primary_id: number
  second_id?: number
  primary_member?: string
  second_member?: string
}): Promise<{ status?: string; message?: string }> {
  const body = await apiFetch<{ status?: boolean; message?: string; data?: unknown }>(`${BASE}/membership`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(payload),
  })
  return { status: body.status ? 'ok' : undefined, message: body.message }
}
