/**
 * Standardized per-platform publish result + overall job status.
 */

import type { SocialPublishErrorCode } from "@/lib/social/publish-errors";

export type PlatformResultStatus =
  | "pending"
  | "processing"
  | "success"
  | "failed"
  | "skipped"
  | "retrying";

export type PublishJobOverallStatus =
  | "DRAFT"
  | "QUEUED"
  | "PROCESSING"
  | "PARTIALLY_PUBLISHED"
  | "PUBLISHED"
  | "FAILED"
  | "CANCELLED";

export interface PlatformPublishResult {
  platform: string;
  status: "success" | "failed" | "skipped";
  errorCode?: SocialPublishErrorCode | string;
  message?: string;
  action?: string;
  retryable?: boolean;
  providerPostId?: string;
  providerUrl?: string;
  publishedAt?: string;
  destination?: string;
  attempt?: number;
}

/** Legacy outcome shape used across the app — keep compatible. */
export interface PlatformPublishOutcome {
  platform: string;
  success: boolean;
  skipped?: boolean;
  postId?: string;
  permalink?: string;
  error?: string;
  errorCode?: string;
  action?: string;
  destination?: string;
  imageAttached?: boolean;
  imageSkipReason?: string;
  retryable?: boolean;
  attempt?: number;
}

export function outcomeToStandardResult(
  outcome: PlatformPublishOutcome,
): PlatformPublishResult {
  const status: PlatformPublishResult["status"] = outcome.success
    ? "success"
    : outcome.skipped
      ? "skipped"
      : "failed";
  return {
    platform: outcome.platform,
    status,
    errorCode: outcome.errorCode,
    message: outcome.error ?? (outcome.success ? "Published successfully" : undefined),
    action: outcome.action,
    retryable: outcome.retryable,
    providerPostId: outcome.postId,
    providerUrl: outcome.permalink,
    publishedAt: outcome.success ? new Date().toISOString() : undefined,
    destination: outcome.destination,
    attempt: outcome.attempt,
  };
}

export function computeOverallPublishStatus(
  results: Array<Pick<PlatformPublishOutcome, "success" | "skipped" | "error">>,
): PublishJobOverallStatus {
  if (!results.length) return "FAILED";
  const successes = results.filter((r) => r.success).length;
  const failures = results.filter((r) => !r.success && !r.skipped).length;
  const skipped = results.filter((r) => r.skipped && !r.success).length;
  if (successes > 0 && (failures > 0 || skipped > 0)) return "PARTIALLY_PUBLISHED";
  if (successes > 0 && failures === 0) return "PUBLISHED";
  return "FAILED";
}
