import { apiRequest } from './api';

export interface ContentEntry {
  id: string;
  name: string;
  entryType?: string;
  route?: string;
  icon?: string;
  sortOrder?: number;
  description?: string;
  regionId?: string | null;
}

export interface DashboardSnapshot {
  entries: ContentEntry[];
  banners: unknown[];
  announcements: unknown[];
  profile: unknown | null;
}

export async function loadStudentDashboard(regionId?: string): Promise<DashboardSnapshot> {
  const [entries, banners, announcements, profile] = await Promise.all([
    apiRequest<{ items?: ContentEntry[] }>('/api/catalog/content-entries', { query: { regionId }, authMode: 'none' }),
    apiRequest<{ items?: unknown[] }>('/api/catalog/banners', { authMode: 'none' }),
    apiRequest<{ items?: unknown[] }>('/api/catalog/announcements', { authMode: 'none' }),
    apiRequest<{ item?: unknown }>('/api/profile/me').catch(() => ({ item: null })),
  ]);
  return {
    entries: entries.items || [],
    banners: banners.items || [],
    announcements: announcements.items || [],
    profile: profile.item || null,
  };
}

export interface RegionItem {
  id: string;
  name: string;
  code?: string;
  shortName?: string;
  isHot?: boolean;
}

export interface ContentNode {
  id: string;
  entryId: string;
  parentId?: string | null;
  name: string;
  nodeType?: string;
  markerType?: string | null;
  depth?: number;
  isLeaf?: boolean;
  isSelectable?: boolean;
  metadata?: Record<string, unknown>;
}

export interface QuestionCollection {
  id: string;
  entryId?: string | null;
  nodeId?: string | null;
  name: string;
  collectionType?: string;
  questionCount?: number;
  durationMinutes?: number | null;
}

export interface PracticeBlueprint {
  id: string;
  entryId?: string | null;
  nodeId?: string | null;
  collectionId?: string | null;
  name: string;
  mode: string;
  questionLimit?: number | null;
  durationMinutes?: number | null;
}

export interface VocabularyUnit {
  id: string;
  name: string;
  description?: string | null;
  wordCount?: number;
  regionId?: string | null;
}

export interface HandbookSubject {
  id: string;
  name: string;
  type?: string | null;
  description?: string | null;
}

export interface HandbookChapter {
  id: string;
  subjectId: string;
  name: string;
  description?: string | null;
}

export interface HandbookEntry {
  id: string;
  chapterId: string;
  title: string;
  summary?: string | null;
  content?: string | null;
}

export interface ScorelineRecord {
  id: string;
  regionId?: string | null;
  schoolId?: string | null;
  majorId?: string | null;
  year: number;
  schoolName?: string | null;
  majorName?: string | null;
  fieldValues?: Record<string, unknown>;
}

export interface ScorelineField {
  id: string;
  legacyId?: string | null;
  regionId?: string | null;
  fieldKey: string;
  fieldName: string;
  fieldType?: string | null;
  unit?: string | null;
  isFilter?: boolean;
  isRequired?: boolean;
  isVisible?: boolean;
  isTrend?: boolean;
  options?: unknown;
  placeholder?: string | null;
  description?: string | null;
  sortOrder?: number;
}

export interface ScorelineSchool {
  id: string;
  legacyId?: string | null;
  regionId?: string | null;
  name: string;
  shortName?: string | null;
  type?: string | null;
  isHot?: boolean;
  order?: number;
}

export interface ScorelineMajor {
  id: string;
  legacyId?: string | null;
  regionId?: string | null;
  schoolId?: string | null;
  name: string;
  order?: number;
  hasRestriction?: boolean;
  restrictionDesc?: string | null;
}

export interface ContentAsset {
  id: string;
  title?: string | null;
  assetType?: string;
  categoryLabel?: string | null;
  description?: string | null;
  fileName?: string | null;
  mimeType?: string | null;
  visibility?: string;
  previewStatus?: string;
}

export interface AssetWatermarkContext {
  mode: 'none' | 'visible_overlay';
  required: boolean;
  text: string;
  traceId: string;
  position: 'diagonal' | 'bottom-right' | 'center';
  opacity: number;
  repeat: boolean;
  expiresAt?: string | null;
  renderHint: string;
}

export interface SignedAssetLink {
  url?: string;
  expiresAt?: string | null;
  expiresInSec?: number | null;
  signatureMode?: string | null;
}

export async function loadRegions() {
  return apiRequest<{ items?: RegionItem[] }>('/api/catalog/regions', { authMode: 'none' });
}

export async function loadContentEntries(regionId?: string, entryType?: string) {
  return apiRequest<{ items?: ContentEntry[] }>('/api/catalog/content-entries', { query: { regionId, entryType }, authMode: 'none' });
}

export async function loadContentNodes(entryId: string, parentId: string | null = 'root', mode: 'children' | 'flat' = 'children') {
  return apiRequest<{ items?: ContentNode[] }>('/api/catalog/content-nodes', { query: { entryId, parentId, mode }, authMode: 'none' });
}

export async function loadQuestionCollections(input: { entryId?: string; nodeId?: string; limit?: number }) {
  return apiRequest<{ items?: QuestionCollection[] }>('/api/catalog/question-collections', {
    query: { entryId: input.entryId, nodeId: input.nodeId, limit: input.limit || 100 },
    authMode: 'none',
  });
}

export async function loadCollectionQuestions(collectionId: string, limit = 200) {
  return apiRequest<{ items?: import('./learning').QuestionItem[] }>('/api/catalog/question-collections/questions', {
    query: { collectionId, limit },
    authMode: 'none',
  });
}

export async function loadQuestions(query: { entryId?: string; contentNodeId?: string; collectionId?: string; questionIds?: string[]; limit?: number }) {
  return apiRequest<{ items?: import('./learning').QuestionItem[] }>('/api/catalog/questions', {
    query: { ...query, questionIds: query.questionIds?.join(','), limit: query.limit || 200 },
    authMode: 'none',
  });
}

export async function loadPracticeBlueprints(input: { entryId?: string; nodeId?: string; collectionId?: string; mode?: string }) {
  return apiRequest<{ items?: PracticeBlueprint[] }>('/api/catalog/practice-blueprints', {
    query: input,
    authMode: 'none',
  });
}

export async function loadVocabularyUnits(regionId?: string) {
  return apiRequest<{ items?: VocabularyUnit[] }>('/api/catalog/vocabulary-units', { query: { regionId }, authMode: 'none' });
}

export async function loadVocabularyWords(unitId: string) {
  return apiRequest<{ items?: import('./learning').VocabularyWord[] }>('/api/catalog/vocabulary-words', { query: { unitId }, authMode: 'none' });
}

export async function loadHandbookSubjects(regionId?: string) {
  return apiRequest<{ items?: HandbookSubject[] }>('/api/catalog/handbook-subjects', { query: { regionId }, authMode: 'none' });
}

export async function loadHandbookChapters(subjectId: string) {
  return apiRequest<{ items?: HandbookChapter[] }>('/api/catalog/handbook-chapters', { query: { subjectId }, authMode: 'none' });
}

export async function loadHandbookEntries(chapterId: string, includeContent = true) {
  return apiRequest<{ items?: HandbookEntry[] }>('/api/catalog/handbook-entries', { query: { chapterId, includeContent }, authMode: 'none' });
}

export async function loadScorelineFields(regionId?: string) {
  return apiRequest<{ items?: ScorelineField[] }>('/api/scoreline/fields', { query: { regionId }, authMode: 'none' });
}

export async function loadScorelineSchools(query: { regionId?: string; q?: string; limit?: number } = {}) {
  return apiRequest<{ items?: ScorelineSchool[] }>('/api/scoreline/schools', {
    query: { ...query, limit: query.limit || 200 },
    authMode: 'none',
  });
}

export async function loadScorelineMajors(query: { regionId?: string; schoolId?: string; limit?: number } = {}) {
  return apiRequest<{ items?: ScorelineMajor[] }>('/api/scoreline/majors', {
    query: { ...query, limit: query.limit || 500 },
    authMode: 'none',
  });
}

export async function loadScorelineYears(regionId?: string) {
  return apiRequest<{ items?: number[] }>('/api/scoreline/years', { query: { regionId }, authMode: 'none' });
}

export async function loadScorelineTrend(query: { regionId?: string; schoolId?: string; majorId?: string; limit?: number } = {}) {
  return apiRequest<{ items?: ScorelineRecord[] }>('/api/scoreline/trend', {
    query: { ...query, limit: query.limit || 20 },
    authMode: 'none',
  });
}

export async function loadScorelineRecords(query: {
  regionId?: string;
  schoolId?: string;
  majorId?: string;
  year?: number;
  page?: number;
  pageSize?: number;
  dynamicFilters?: Record<string, string | number | boolean | null | undefined>;
  dynamicMinFilters?: Record<string, string | number | null | undefined>;
  dynamicMaxFilters?: Record<string, string | number | null | undefined>;
} = {}) {
  const dynamicQuery: Record<string, string | number | boolean | null | undefined> = {};
  Object.entries(query.dynamicFilters || {}).forEach(([key, value]) => {
    dynamicQuery[`field.${key}`] = value;
  });
  Object.entries(query.dynamicMinFilters || {}).forEach(([key, value]) => {
    dynamicQuery[`min.${key}`] = value;
  });
  Object.entries(query.dynamicMaxFilters || {}).forEach(([key, value]) => {
    dynamicQuery[`max.${key}`] = value;
  });
  return apiRequest<{ items?: ScorelineRecord[]; total?: number }>('/api/scoreline/records', {
    query: {
      regionId: query.regionId,
      schoolId: query.schoolId,
      majorId: query.majorId,
      year: query.year,
      page: query.page,
      pageSize: query.pageSize || 20,
      ...dynamicQuery,
    },
    authMode: 'none',
  });
}

export async function loadContentAssets(query: { entryId?: string; contentNodeId?: string; assetType?: string; includeLocked?: boolean } = {}) {
  return apiRequest<{ items?: ContentAsset[] }>('/api/catalog/assets', { query: { ...query, includeLocked: query.includeLocked ?? true } });
}

export async function signAssetPreview(assetId: string) {
  return apiRequest<{ preview?: SignedAssetLink; item?: ContentAsset; watermark?: AssetWatermarkContext }>('/api/catalog/assets/preview', { query: { assetId } });
}

export async function signAssetDownload(assetId: string) {
  return apiRequest<{ download?: SignedAssetLink; item?: ContentAsset; watermark?: AssetWatermarkContext }>('/api/catalog/assets/download', { query: { assetId } });
}
