import type { Project, TargetMarket } from "@/types/workflow";

/**
 * Suggested IANA zones per country for *future* multi-market scheduling.
 * Current publishing always uses the project's primary timezone.
 */
export const COUNTRY_DEFAULT_TIMEZONES: Record<string, string> = {
  US: "America/New_York",
  GB: "Europe/London",
  IN: "Asia/Kolkata",
  CA: "America/Toronto",
};

export function buildTargetMarkets(
  countries: string[],
  projectTimezone: string,
  existing?: TargetMarket[],
): TargetMarket[] {
  return countries.map((countryCode) => {
    const prior = existing?.find((m) => m.countryCode === countryCode);
    return {
      countryCode,
      // Store a country-suggested zone for future market slots; scheduling today uses project.timezone.
      timezone: prior?.timezone || COUNTRY_DEFAULT_TIMEZONES[countryCode],
      audienceTimePreference: prior?.audienceTimePreference || "",
    };
  });
}

export function withProjectTargetMarkets(project: Project): Project {
  return {
    ...project,
    targetMarkets: buildTargetMarkets(
      project.countries,
      project.timezone,
      project.targetMarkets,
    ),
  };
}

/** Slot planning timezone for a market — falls back to the project timezone. */
export function resolveMarketTimezone(project: Project, market?: TargetMarket): string {
  const override = market?.timezone?.trim();
  if (override) return override;
  return project.timezone;
}
