import apiClient from "@/lib/axiosClient";
import { API_ENDPOINTS } from "@/lib/apiEndpoints";
import { formatRelativeDate } from "@/utils/format";

export interface RawNotification {
  id: number;
  type: number; // 1=general, 2=like, 3=comment, 4=subscribe
  title: string;
  message: string;
  storage_type: number;
  image: string;
  user_id: number;
  from_user_id: number;
  content_id: number;
  status: number; // 1=unread, 2=read
  created_at: string;
  updated_at: string;
  user_name: string;
  user_image: string;
  content_name: string;
  content_image: string;
}

export interface NotificationItem {
  id: string;
  type: number;
  title: string;
  message: string;
  userId: string;
  fromUserId: string;
  contentId: string;
  isRead: boolean;
  createdAt: string;
  userName: string;
  userImage: string;
  contentName: string;
  contentImage: string;
}

export interface NotificationResponse {
  status: number;
  message: string;
  result: RawNotification[];
  total_rows: number;
  total_page: number;
  current_page: number;
  more_page: boolean;
}

function mapNotification(raw: RawNotification): NotificationItem {
  return {
    id: String(raw.id),
    type: raw.type,
    title: raw.title,
    message: raw.message || "",
    userId: String(raw.user_id),
    fromUserId: String(raw.from_user_id),
    contentId: String(raw.content_id),
    isRead: raw.status === 2,
    createdAt: formatRelativeDate(raw.created_at),
    userName: raw.user_name || "",
    userImage: raw.user_image || "",
    contentName: raw.content_name || "",
    contentImage: raw.content_image || "",
  };
}

export const notificationService = {
  getNotifications: (pageNo: number): Promise<NotificationResponse> =>
    apiClient
      .post(API_ENDPOINTS.GET_NOTIFICATION, { page_no: pageNo })
      .then((r) => r.data),

  readNotification: (notificationId: string): Promise<void> =>
    apiClient
      .post(API_ENDPOINTS.READ_NOTIFICATION, { notification_id: notificationId })
      .then(() => {}),

  mapNotification,
};
