import { API_ENDPOINTS } from '@/shared/constants/apiEndpoints';
import { api } from '@/shared/utils/api';
import { isPaginatedResponse } from '@/shared/types/pagination.types';

export interface NotificationTemplateRecord {
  id: string;
  department_id: string | null;
  is_global: boolean;
  type: string;
  channel: string;
  subject_en: string;
  subject_ar: string;
  body_en: string;
  body_ar: string;
  variables: string[];
  is_active: boolean;
}

function isTemplate(v: unknown): v is NotificationTemplateRecord {
  return typeof v === 'object' && v !== null && typeof (v as NotificationTemplateRecord).id === 'string';
}

export async function listNotificationTemplates(
  departmentId?: string,
): Promise<NotificationTemplateRecord[]> {
  const query = departmentId ? `?department_id=${encodeURIComponent(departmentId)}` : '';
  const raw: unknown = await api.get(`${API_ENDPOINTS.NOTIFICATION_TEMPLATES.LIST}${query}`);
  if (isPaginatedResponse(raw, isTemplate)) {
    return raw.data;
  }
  if (typeof raw === 'object' && raw !== null && 'data' in raw) {
    const data = (raw as { data: unknown }).data;
    if (Array.isArray(data) && data.every(isTemplate)) {
      return data;
    }
  }
  return [];
}

export async function updateNotificationTemplate(
  id: string,
  payload: Partial<NotificationTemplateRecord>,
): Promise<NotificationTemplateRecord> {
  const raw: unknown = await api.patch(API_ENDPOINTS.NOTIFICATION_TEMPLATES.UPDATE(id), payload);
  if (isTemplate(raw)) {
    return raw;
  }
  if (typeof raw === 'object' && raw !== null && 'data' in raw) {
    const data = (raw as { data: unknown }).data;
    if (isTemplate(data)) {
      return data;
    }
  }
  throw new Error('Invalid template response');
}

export async function customizeNotificationTemplate(
  id: string,
  departmentId: string,
): Promise<NotificationTemplateRecord> {
  const raw: unknown = await api.post(API_ENDPOINTS.NOTIFICATION_TEMPLATES.CUSTOMIZE(id), {
    department_id: departmentId,
  });
  if (isTemplate(raw)) {
    return raw;
  }
  if (typeof raw === 'object' && raw !== null && 'data' in raw) {
    const data = (raw as { data: unknown }).data;
    if (isTemplate(data)) {
      return data;
    }
  }
  throw new Error('Invalid template response');
}

export async function resetNotificationTemplate(id: string): Promise<NotificationTemplateRecord> {
  const raw: unknown = await api.post(API_ENDPOINTS.NOTIFICATION_TEMPLATES.RESET(id));
  if (isTemplate(raw)) {
    return raw;
  }
  if (typeof raw === 'object' && raw !== null && 'data' in raw) {
    const data = (raw as { data: unknown }).data;
    if (isTemplate(data)) {
      return data;
    }
  }
  throw new Error('Invalid template response');
}
