import { normalizeSequenceItem } from "@/lib/context/sequence-templates";
import type {
  BrandProfile,
  ConnectedAccount,
  PostingContextData,
  PostSequenceItem,
  Project,
  ProjectStatus,
} from "@/types/workflow";
import {
  createDefaultScopedData,
  createEmptyProject,
  mergeProjectAccounts,
  type ProjectScopedData,
} from "./defaults";

type LegacyProject = {
  name?: string;
  website?: string;
  industry?: string;
  timezone?: string;
  countries?: string[];
  status?: ProjectStatus;
  created?: boolean;
};

export function migrateLegacyStores(input: {
  legacyProject?: LegacyProject | null;
  legacyBrand?: Partial<BrandProfile> | null;
  legacyContext?: {
    context?: PostingContextData;
    selectedPostId?: string | null;
  } | null;
  legacyAccounts?: { accounts?: ConnectedAccount[] } | null;
}): {
  projects: Project[];
  activeProjectId: string | null;
  dataByProjectId: Record<string, ProjectScopedData>;
} {
  const legacy = input.legacyProject;
  if (!legacy?.created || !legacy.name?.trim()) {
    return { projects: [], activeProjectId: null, dataByProjectId: {} };
  }

  const project = createEmptyProject({
    name: legacy.name,
    website: legacy.website ?? "",
    industry: legacy.industry ?? "Technology / Software",
    timezone: legacy.timezone ?? "America/New_York (EST)",
    countries: legacy.countries ?? ["US", "GB", "IN", "CA"],
    status: legacy.status ?? "active",
  });

  const defaults = createDefaultScopedData();
  const data: ProjectScopedData = {
    ...defaults,
    brand: { ...defaults.brand, ...input.legacyBrand },
    context: input.legacyContext?.context ?? defaults.context,
    selectedPostId: input.legacyContext?.selectedPostId ?? defaults.selectedPostId,
    accounts: mergeProjectAccounts(input.legacyAccounts?.accounts),
  };

  return {
    projects: [project],
    activeProjectId: project.id,
    dataByProjectId: { [project.id]: data },
  };
}

export function patchScopedContextPosts(
  posts: Array<
    Partial<PostSequenceItem> & {
      description?: string;
      problem?: string;
      impact?: string;
      hashtags?: string;
    }
  >,
): PostSequenceItem[] {
  return posts.map((post, index) => normalizeSequenceItem(post, index));
}
