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 lines?: readonly CommentLine[] }): string {
	const nonEmptyLines = options?.lines?.filter((m) => m.value) ?? [];

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

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

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

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

export function getEnvironmentInfoComment(data: {
	readonly timestampDate?: Date;
	readonly environmentInfo: Readonly<EnvironmentModels.EnvironmentInformationModel>;
}): string {
	return `
/*
 * This file has been auto-generated by '${sdkInfo.name}@${sdkInfo.version}'.
 * 
 * (c) Kontent.ai
 *  
 * -------------------------------------------------------------------------------
 * 
 * Project: ${toSafeComment(data.environmentInfo.name)}
 * Environment: ${toSafeComment(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, " ");
}
