import { getApiBaseUrl } from "@/components/main/BaseUrl";
import type { PostLinkKind } from "@/lib/postLinkCaption";

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

/** اورلی لینک روی استوری — همون ۶ مورد قابل‌لینک ثبت پست (پکیج/پروژه/بیلبورد/فروشگاه/کالا/رزرو) */
export type StoryLinkOverlay = {
  type: "link";
  link_kind: PostLinkKind;
  link_id: string;
  link_title: string;
  x: number;
  y: number;
  rotation?: number;
};

export type StoryOverlay = StoryTextOverlay | StoryLinkOverlay;

export type StoryItem = {
  _id: string;
  media_path: string;
  media_type: "image" | "video";
  linked_post_id?: string | null;
  overlays?: StoryOverlay[];
  createdAt?: string;
  expires_at?: string;
  viewed?: boolean;
  liked?: boolean;
  likes_count?: number;
};

export type StoryFeedUser = {
  user: {
    _id: string;
    user_name: string;
    first_name: string;
    last_name: string;
    profile_image?: string;
    verify_badge?: string;
  };
  stories: StoryItem[];
  has_unviewed: boolean;
  is_following?: 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: StoryOverlay[] = []
): 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: StoryOverlay[],
  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 || "خطا در ویرایش استوری");
  }
}

export type StoryViewerUser = {
  _id: string;
  user_name: string;
  first_name: string;
  last_name: string;
  profile_image?: string;
  viewed_at?: string;
};

export async function likeStory(
  storyId: string,
  token: string
): Promise<{ liked: boolean; already?: boolean }> {
  const res = await fetch(`${getApiBaseUrl()}/stories/like`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify({ storyId }),
  });
  if (!res.ok) {
    const json = await res.json().catch(() => ({}));
    throw new Error(json?.message || "خطا در لایک استوری");
  }
  return res.json();
}

export async function commentOnStory(
  storyId: string,
  comment: string,
  token: string
): Promise<void> {
  const res = await fetch(`${getApiBaseUrl()}/stories/comment`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify({ storyId, comment }),
  });
  if (!res.ok) {
    const json = await res.json().catch(() => ({}));
    throw new Error(json?.message || "خطا در ارسال کامنت");
  }
}

export async function fetchStoryViewers(
  storyId: string,
  token: string
): Promise<{ viewers: StoryViewerUser[]; total: number }> {
  const res = await fetch(`${getApiBaseUrl()}/stories/${storyId}/viewers`, {
    headers: { Authorization: `Bearer ${token}` },
  });
  if (!res.ok) {
    const json = await res.json().catch(() => ({}));
    throw new Error(json?.message || "خطا در دریافت بازدیدکنندگان");
  }
  return res.json();
}

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