import { StudentAffairsDocument } from '@/types'

const API_BASE = (process.env.NEXT_PUBLIC_AAU_API_BASE_URL || process.env.AAU_API_BASE_URL || 'https://edu.yemenfrappe.com').replace(/\/$/, '')
const STUDENT_AFFAIRS_ENDPOINT = '/api/aau/student-affairs/docs'

const FALLBACK_DOCS: StudentAffairsDocument[] = [
  {
    id: 'student-affairs-regulations',
    titleAr: 'لائحة شؤون الطلاب',
    titleEn: 'Student Affairs Regulations',
    href: '/docs/regulations.pdf',
    fileComingSoon: true,
    displayOrder: 1,
  },
  {
    id: 'supplementary-semester',
    titleAr: 'الدوري التكميلي',
    titleEn: 'Supplementary Semester',
    href: '/docs/supplementary.pdf',
    fileComingSoon: true,
    displayOrder: 2,
  },
  {
    id: 'grievance-form',
    titleAr: 'استمارة تظلمات',
    titleEn: 'Grievance Form',
    href: '/docs/grievance.pdf',
    fileComingSoon: true,
    displayOrder: 3,
  },
  {
    id: 'general-conduct',
    titleAr: 'ضوابط وسلوكيات عامة',
    titleEn: 'General Behavior Controls',
    href: '/docs/general_conduct.pdf',
    fileComingSoon: true,
    displayOrder: 4,
  },
  {
    id: 'exam-conduct',
    titleAr: 'ضوابط وسلوكيات الامتحانات',
    titleEn: 'Exam Behavior Controls',
    href: '/docs/exam_conduct.pdf',
    fileComingSoon: true,
    displayOrder: 5,
  },
]

function unwrapPayload(payload: any) {
  if (payload?.ok && payload?.data !== undefined) {
    return payload.data
  }
  if (payload?.message?.ok && payload?.message?.data !== undefined) {
    return payload.message.data
  }
  if (payload?.data?.ok && payload?.data?.data !== undefined) {
    return payload.data.data
  }
  if (payload?.data !== undefined) {
    return payload.data
  }
  return payload
}

function mapDoc(item: any): StudentAffairsDocument {
  return {
    id: String(item?.id || ''),
    titleAr: String(item?.titleAr || ''),
    titleEn: String(item?.titleEn || ''),
    href: String(item?.href || ''),
    fileComingSoon: Boolean(item?.fileComingSoon ?? true),
    displayOrder: Number(item?.displayOrder ?? 0),
  }
}

export async function getStudentAffairsDocuments(): Promise<StudentAffairsDocument[]> {
  try {
    const response = await fetch(`${API_BASE}${STUDENT_AFFAIRS_ENDPOINT}`, {
      headers: { Accept: 'application/json' },
      cache: 'no-store',
    })

    if (!response.ok) {
      return FALLBACK_DOCS
    }

    const payload = await response.json()
    const data = unwrapPayload(payload)
    const items = Array.isArray(data?.items) ? data.items : []
    const docs = items.map(mapDoc).filter((item) => item.id && (item.titleAr || item.titleEn))
    return docs.length ? docs : FALLBACK_DOCS
  } catch {
    return FALLBACK_DOCS
  }
}
