import { BlockDeprecation } from "@wordpress/blocks";
import { TitleIdType, TitleObjectType, TitleSelection } from "../types";
import { generateShortcode } from "./save";

type V1 = {
  titleId?: number;
  titleType?: TitleObjectType;
  seasonNumber?: number;
  episodeNumber?: number;
  titleName?: string;
  titleReleaseYear?: number;
  titleDirector?: string;
};

const v1: BlockDeprecation<TitleSelection> = {
  attributes: {
    titleId: { type: "number" },
    titleType: { type: "string" },
    seasonNumber: { type: "number" },
    episodeNumber: { type: "number" },
    titleName: { type: "string" },
    titleReleaseYear: { type: "number" },
    titleDirector: { type: "string" },
  },
  migrate(attributes: V1 & TitleSelection): TitleSelection {
    return {
      id: attributes.titleId?.toString() ?? "",
      idType: attributes.idType ?? "justwatch" as TitleIdType,
      objectType: (attributes.titleType ?? "movie") as TitleObjectType,
      seasonNumber: attributes.seasonNumber ?? (attributes.titleType === "show" ? 1 : undefined),
      episodeNumber: attributes.episodeNumber ?? (attributes.titleType === "show" ? 1 : undefined),
      meta: {
        justwatchId: Number(attributes.titleId),
        title: attributes.titleName ?? "",
        objectType: (attributes.titleType ?? "movie") as TitleObjectType,
        originalTitle: attributes.titleName ?? "",
        originalReleaseYear: attributes.titleReleaseYear ?? 0,
        director: attributes.titleDirector ?? "",
      },
    };
  },
  save: ({ attributes }: { attributes: Partial<V1 & TitleSelection> }): string => {
    const {
      titleId,
      titleType,
      seasonNumber,
      episodeNumber
    } = attributes;

    const id = attributes.id || titleId?.toString();
    const objectType = attributes.objectType || titleType;

    if (!id || !objectType) {
      return "";
    }

    const isLegacy = titleId !== undefined || titleType !== undefined;

    const idType = attributes.idType || "justwatch";

    const code = generateShortcode({
      id,
      idType,
      objectType,
      seasonNumber: seasonNumber ?? (objectType === "show" ? 1 : undefined),
      episodeNumber: episodeNumber ?? (objectType === "show" ? 1 : undefined),
    }, {
      keyMap: isLegacy ? {
        idType: null,
        episodeNumber: "episode",
        seasonNumber: "season",
        objectType: "type"
      } : {},
    });

    return code;
  },
}

export default [ v1 ];