import type { File, InputExportedV1, Rule } from "~/shared/models"
import { ruleTypes } from "~/shared/models/enums.generated"

export function fromLegacy(oldJSON: {
  directories: {
    id: number
    name: string
  }[]
  files: {
    name: string
    content: string
    createdAt: string
    updatedAt: string
    id: number
    parentId?: number
    metadata: {
      enabled: boolean
      rules: (Omit<Rule, "exclude"> & { negative?: boolean })[]
    }
  }[]
}): File[] {
  const directoryMap = new Map<number, string>(
    oldJSON.directories.map(directory => [directory.id, directory.name]),
  )
  return oldJSON.files.map(
    (file): File => ({
      id: undefined!,
      name: file.name,
      enabled: file.metadata.enabled,
      mimeType: "text/x-scss",
      hidden: false,
      rules: file.metadata.rules
        .filter(({ type }) => ruleTypes.includes(type))
        .map(({ negative, ...rule }) => ({
          ...rule,
          exclude: negative ?? false,
        })),
      state: null,
      createdAt: new Date(file.createdAt),
      updatedAt: new Date(file.updatedAt),
      sections: [
        {
          id: "0",
          name: "",
          code: file.content,
          enabled: true,
        },
      ],
      tags: (() => {
        const tag = directoryMap.get(file.parentId ?? 0)
        return tag ? [tag] : []
      })(),
    }),
  )
}

export function v1ToNow(value: InputExportedV1): File[] {
  return value.files
}
