import type { EnvironmentModels } from "@kontent-ai/management-sdk";
import { sdkInfo } from "../sdk-info.js";

export type CommentLine = {
	readonly name: string;
	readonly value: string | undefined;
};

export function wrapComment(
	comment: string,
	options: {
		readonly disableComments: boolean;
		readonly lines?: readonly CommentLine[];
	},
): string {
	if (options.disableComments) {
		return "";
	}
	const nonEmptyLines = options.lines?.filter((m) => m.value) ?? [];

	if (!nonEmptyLines.length) {
		return `/*\n* ${toSafeCommentText(comment)}\n*/`;
	}

	return `/*
    * ${toSafeCommentText(comment)}
    *
    ${nonEmptyLines.map((m) => `* ${m.name}: ${m.value}`).join("\n")}
    */`;
}

export function toSafeCommentText(text: string): string {
	const replaceContent = "";
	return text.replace(/\/\*/g, replaceContent).replace(/\*\//g, replaceContent);
}

export function formatGuidelinesComment(guidelines: string): string {
	return removeLineEndings(guidelines);
}

export function getEnvironmentInfoComment(data: {
	readonly timestampDate?: Date;
	readonly disableComments: boolean;
	readonly environmentInfo: Readonly<EnvironmentModels.EnvironmentInformationModel>;
}): string {
	if (data.disableComments) {
		return "";
	}
	return `
/*
 * This file has been auto-generated by '${sdkInfo.name}@${sdkInfo.version}'.
 *
 * (c) Kontent.ai
 *
 * -------------------------------------------------------------------------------
 *
 * Project: ${toSafeCommentText(data.environmentInfo.name)}
 * Environment: ${toSafeCommentText(data.environmentInfo.environment)}
 * Id: ${data.environmentInfo.id}${data.timestampDate ? `\n* Generated: ${data.timestampDate.toLocaleString()}` : ""}
 *
 * -------------------------------------------------------------------------------
 */`;
}

function removeLineEndings(value: string): string {
	return value.replace(/(\r\n|\n|\r)/g, " ");
}
