import { AttioObject } from "../../helpers/fetchAttioSchema";
import { writeGeneratedFile } from "../../helpers/fs";
import logger from "../../helpers/logger";
import { generateFileHeader } from "./fileHeader";

const FILE_NAME = "sdk-utilities.ts";

export function generateSdkUtilityTypes(objects: AttioObject[], standardTypes: boolean = false, outputDir: string): void {
  logger.debug(`Generating SDK utility types file: ${FILE_NAME}`);

  const imports = `${objects.map(({ singular_noun }) => singular_noun).join(", ")}, ${standardTypes ? "AttioList, AttioEntry, AttioNote, AttioTask" : ""}`;

  const entityNames = [...objects.map(({ api_slug }) => `'${api_slug}'`), ...(standardTypes ? [`'list'`, `'entry'`, `'note'`, `'task'`] : [])];

  const entityTypes = [
    ...objects.map(({ api_slug, singular_noun }) => `  '${api_slug}': ${singular_noun};`),
    ...(standardTypes ? [`  'list': AttioList;`, `  'entry': AttioEntry;`, `  'note': AttioNote;`, `  'task': AttioTask;`] : []),
  ];

  const utilityTypes = `
${generateFileHeader(FILE_NAME)}
import { ${imports} } from ".";

/**
 * All available entity names in your Attio workspace.
 * Use this type for type-safe entity access with the SDK.
 */
export type EntityName = ${entityNames.join(" | ")};

/**
 * Maps entity names to their corresponding types.
 * Use this for type-safe entity access in your SDK.
 */
export interface EntityTypes {
${entityTypes.join("\n")}
}

/**
 * Type utility to get the entity type from an entity name.
 */
export type GetEntityType<K extends EntityName> = EntityTypes[K];
`;

  writeGeneratedFile(outputDir, FILE_NAME, utilityTypes);
}
