import type { ContentMediaType, ContentOrigin } from "@/types/workflow";
import { buildContentPost, type CreateContentPostInput } from "./post-model";

export interface ManualPostBody {
  projectId: string;
  title?: string;
  caption: string;
  hashtags?: string[] | string;
  linkUrl?: string;
  cta?: string;
  mediaType?: ContentMediaType;
  platforms?: string[];
  imageUrl?: string | null;
  videoUrl?: string | null;
  sequencePostId?: string;
}

export function parseHashtags(raw: string[] | string | undefined): string[] {
  if (!raw) return [];
  if (Array.isArray(raw)) return raw.map((h) => h.trim()).filter(Boolean);
  return raw
    .split(/[;,|\s]+/)
    .map((h) => h.trim().replace(/^#/, ""))
    .filter(Boolean);
}

export function validateManualPostBody(body: ManualPostBody): string | null {
  if (!body.projectId?.trim()) return "projectId is required";
  if (!body.caption?.trim()) return "caption is required";
  if (body.caption.length > 5000) return "caption exceeds maximum length (5000)";
  return null;
}

export function createManualPostInput(
  userId: string,
  body: ManualPostBody,
  project: CreateContentPostInput["project"],
  brand: CreateContentPostInput["brand"],
  context?: CreateContentPostInput["context"],
): CreateContentPostInput {
  return {
    userId,
    project,
    brand,
    context,
    origin: "manual" as ContentOrigin,
    title: body.title,
    caption: body.caption,
    hashtags: parseHashtags(body.hashtags),
    linkUrl: body.linkUrl,
    cta: body.cta,
    mediaType: body.mediaType,
    platforms: body.platforms?.length ? body.platforms : ["linkedin"],
    imageUrl: body.imageUrl,
    videoUrl: body.videoUrl,
    sequencePostId: body.sequencePostId,
    status: "draft",
  };
}

export { buildContentPost };
