import { getApiBaseUrl } from "@/components/main/BaseUrl";

export type StoryTextOverlay = {
  text: string;
  x: number;
  y: number;
  font_size: number;
  color: string;
  background?: string;
  rotation?: number;
  align?: "left" | "center" | "right";
};

export type StoryItem = {
  _id: string;
  media_path: string;
  media_type: "image" | "video";
  overlays?: StoryTextOverlay[];
  createdAt?: string;
  expires_at?: string;
  viewed?: boolean;
};

export type StoryFeedUser = {
  user: {
    _id: string;
    user_name: string;
    first_name: string;
    last_name: string;
    profile_image?: string;
  };
  stories: StoryItem[];
  has_unviewed: boolean;
};

export type StoriesFeedResponse = {
  feed: StoryFeedUser[];
  my_story: StoryFeedUser | null;
  viewer_id: string | null;
};

export async function fetchStoriesFeed(
  token: string
): Promise<StoriesFeedResponse> {
  const res = await fetch(`${getApiBaseUrl()}/stories/feed`, {
    cache: "no-store",
    headers: {
      Authorization: token ? `Bearer ${token}` : "",
    },
  });
  if (!res.ok) throw new Error("Failed to load stories");
  return res.json();
}

export async function markStoryViewed(
  storyId: string,
  token: string
): Promise<void> {
  await fetch(`${getApiBaseUrl()}/stories/view`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify({ storyId }),
  });
}

export async function createStoryBase64(
  file: { name: string; type: string; data: string },
  token: string,
  overlays: StoryTextOverlay[] = []
): Promise<void> {
  const res = await fetch(`${getApiBaseUrl()}/stories/create-base64`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify({ file, overlays }),
  });
  if (!res.ok) {
    const json = await res.json().catch(() => ({}));
    throw new Error(json?.message || "خطا در انتشار استوری");
  }
}

export async function updateStoryOverlays(
  storyId: string,
  overlays: StoryTextOverlay[],
  token: string
): Promise<void> {
  const res = await fetch(`${getApiBaseUrl()}/stories/${storyId}`, {
    method: "PATCH",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify({ overlays }),
  });
  if (!res.ok) {
    const json = await res.json().catch(() => ({}));
    throw new Error(json?.message || "خطا در ویرایش استوری");
  }
}
