
var formattedAuthHeader;
var releaseId;
var releaseName;
var azureAuthenticationHeader;
var baseAPIUrl = '';
var publisherId = "";
var extensionId = "";

$("#notEnoughTokens").hide();
IndexLibrary.InitializeSDK().then(async function () {
    azureAuthenticationHeader = await IndexLibrary.GetAccessToken();
    const orgName = await IndexLibrary.GetAccountNameAsync();

    const urlParams = new URLSearchParams(window.location.search);
    releaseId = urlParams.get('rId');
    releaseName = urlParams.get('rName');

    $("#headerLabel").text('Release notes for ' + releaseName.toString());
    $("#processing").hide();

    const config = await IndexLibrary.GetExtensionConfig();
    baseAPIUrl = config.apiBaseUrl;
    extensionId = config.extensionId;
    publisherId = config.publisherId;
    await GetReleaseNotes();

    window.__releaseNotesOrgName = orgName;

});

$(document).on('click', '#btnCreateReleaseNotes', async function () {

    $("#processing").show();
    $("#releaseNotes").hide();
    await GenerateReleaseNotes();
});

async function GetReleaseNotes() {

    try {
        $("#notesLoading").show();
        $("#releaseNotes").hide();
        $("#lastUpdatedDate").text("—");

        const response = await IndexLibrary.GetRequest({
            endpoint: `/api/Release/GetReleaseNotes/?releaseId=${releaseId}`
        });

        if (response.status === 404) {
            $("#releaseNotes").val("").hide();
            $("#lastUpdatedDate").text("N/A");
            await GenerateReleaseNotes();
        }

        if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);

        const releaseData = await response.json();
        $("#notesLoading").hide();
        $("#releaseNotes").val(releaseData.notes ?? "").show();
        $("#lastUpdatedDate").text(releaseData.modifiedDate
            ? new Date(releaseData.modifiedDate).toLocaleString()
            : "N/A");
    } catch (err) {
        console.error("GetReleaseNotes error:", err);
        $("#releaseNotes").val("").hide();
        $("#lastUpdatedDate").text("N/A");
    }
}

async function GenerateReleaseNotes() {

    const hasLicense = await CheckLicense();
    if (hasLicense) {

        try {
            $("#processing").show();
            $("#releaseNotes").hide();
            $("#notesLoading").hide();

            const devOpsProjectId = await IndexLibrary.GetCurrentProjectId();
            const devOpsProjectName = await IndexLibrary.GetCurrentProjectName();
            const orgName = await IndexLibrary.GetAccountNameAsync();

            const response = await IndexLibrary.GetRequest({
                endpoint: `/api/Release/GenerateReleaseNotes/?releaseId=${releaseId}&organizationName=${orgName}&DevOpsProjectId=${devOpsProjectId}&DevOpsProjectName=${devOpsProjectName}&CreatedBy=${IndexLibrary.GetUserEmail()}`
            });

            const responseText = await response.text();

            if (response.status === 404) {
                $("#releaseNotes").val("").hide();
                $("#lastUpdatedDate").text("N/A");
                $("#processing").hide();
                return;
            }

            if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);

            const releaseData = JSON.parse(responseText);

            $("#releaseNotes").val(releaseData.notes ?? "").show();
            $("#lastUpdatedDate").text(releaseData.modifiedDate
                ? new Date(releaseData.modifiedDate).toLocaleString()
                : "N/A");
        } catch (err) {
            console.error("GenerateReleaseNotes error:", err);
            $("#releaseNotes").val("").hide();
            $("#lastUpdatedDate").text("N/A");
        } finally {
            $("#processing").hide();
        }
    }
    else {
        $("#releaseNotes").show();
        $("#processing").hide();


    }
}
async function CheckLicense() {
    try {
        const response = await IndexLibrary.PostRequest({
            endpoint: '/api/License/GetLicense',
            body: {
                organizationName: await IndexLibrary.GetAccountNameAsync()
            }
        });

        if (!response.ok) {
            throw new Error("Failed to fetch license");
        }

        const licenseData = await response.json();
        console.log("License data:", licenseData);

        const warningEl = $("#LicenseWarning");
        const containerEl = $("#licenseWarningContainer");
        const actionBtn = $("#btnCreateReleaseNotes");


        if (!licenseData || Object.keys(licenseData).length === 0) {
            warningEl.text(
                "You are not authorized to perform this action. Please contact your organization administrator."
            );
            containerEl.show();
            actionBtn.hide();
            return false;
        }

        const expiryDate = licenseData.expiryDateTimeUtc
            ? new Date(licenseData.expiryDateTimeUtc)
            : null;

        const now = new Date();

        if (
            licenseData.licenseType == null ||
            licenseData.isDeleted === true ||
            (expiryDate && expiryDate < now)
        ) {
            warningEl.text("Your license is invalid or has expired.");
            containerEl.show();
            actionBtn.hide();
            return false;
        }

        // ✅ Valid license
        containerEl.hide();
        actionBtn.show();
        return true;

    } catch (err) {
        console.error("Error checking license:", err);

        $("#LicenseWarning").text(
            "Error checking license. Contact your organization administrator."
        );
        $("#licenseWarningContainer").show();
        $("#btnCreateReleaseNotes").hide();

        return false;
    }
}


async function NavigateToReleaseDetails() {
    const orgName = await IndexLibrary.GetAccountNameAsync();
    const projectName = await IndexLibrary.GetCurrentProjectName();

    let newUrl = document.referrer && document.referrer.includes("create-release.html")
        ? `https://dev.azure.com/${orgName}/${projectName}/_apps/hub/${publisherId}.${extensionId}.release-groups-hub-group.create-release?rId=${releaseId}`
        : `https://dev.azure.com/${orgName}/${projectName}/_apps/hub/${publisherId}.${extensionId}.release-groups-hub-group.list-releases`;

    IndexLibrary.NavigateToUrl(newUrl);
}