import { apiRequest } from "./client";
import { arr, normalizeActivity } from "../utils/normalizers";

function normalizeActivityListResponse(data: any) {
  if (Array.isArray(data)) return data.map(normalizeActivity);
  return {
    ...data,
    publicActivities: arr(data?.publicActivities).map(normalizeActivity),
    myPendingActivities: arr(data?.myPendingActivities).map(normalizeActivity),
    items: Array.isArray(data?.items) ? data.items.map(normalizeActivity) : undefined,
    records: Array.isArray(data?.records) ? data.records.map(normalizeActivity) : undefined,
  };
}

export function getActivities() {
  return apiRequest("/api/activities").then(normalizeActivityListResponse);
}

export function registerActivity(id) {
  return apiRequest(`/api/activities/${id}/register`, { method: "POST" });
}

export function getActivityDetail(id) {
  return apiRequest(`/api/activities/${id}`).then(normalizeActivity);
}

export function checkinSelfScan(id, checkinCode) {
  return apiRequest(`/api/activities/${id}/checkins/self-scan`, {
    method: "POST",
    data: { checkinCode }
  });
}

export function createActivity(data) {
  return apiRequest("/api/activities", {
    method: "POST",
    data
  });
}

export function updateActivity(id, data) {
  return apiRequest(`/api/activities/${id}`, {
    method: "PUT",
    data
  });
}

export function resubmitActivity(id) {
  return apiRequest(`/api/activities/${id}/resubmit`, {
    method: "POST"
  });
}


// 活动专栏
export function getActivityColumns() {
  return apiRequest("/api/activity-columns");
}

export function getColumnActivities(columnId: number | string) {
  return apiRequest(`/api/activity-columns/${columnId}/activities`).then((data) => arr(data).map(normalizeActivity));
}
