import { DsgContext, Module } from "@amplication/code-gen-types";
import { readFile, print } from "@amplication/code-gen-utils";
import { builders } from "ast-types";
import { namedTypes } from "ast-types/gen/namedTypes";
import { OperationCanceledException } from "typescript";
import {
  addImports,
  importNames,
  interpolate,
  removeTSClassDeclares,
} from "./ast";

export async function mapAuthTemplate(
  context: DsgContext,
  templatePath: string,
  fileName: string
): Promise<Module> {
  const { entities, resourceInfo, serverDirectories } = context;
  const authEntity = entities?.find(
    (x) => x.name === resourceInfo?.settings.authEntityName
  );
  if (!authEntity) throw OperationCanceledException; //todo: handle the exception

  const entityInfoName = `${authEntity?.name}Info`;
  const template = await readFile(templatePath);
  const authEntityNameId = builders.identifier(entityInfoName);

  const entityNamImport = importNames(
    [authEntityNameId],
    `./${entityInfoName}`
  );

  addImports(
    template,
    [entityNamImport].filter(
      (x) => x //remove nulls and undefined
    ) as namedTypes.ImportDeclaration[]
  );

  const templateMapping = {
    ENTITY_NAME_INFO: builders.identifier(`${authEntity.name}Info`),
  };

  const filePath = `${serverDirectories.authDirectory}/${fileName}`;

  interpolate(template, templateMapping);
  removeTSClassDeclares(template);

  return {
    code: print(template).code,
    path: filePath,
  };
}
