<%@ page language="java" contentType="text/html; charset=utf-8" %>
<%@ page import="java.io.*" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ include file="/jsp/common/include/localemessage.jsp" %>
<%
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Expires", "0");
%>

<html>
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <jsp:include page="/jsp/common/include/css.jsp"/>
    <jsp:include page="/jsp/common/include/script.jsp"/>

    <script language="javascript">
        var url = '<c:url value="/onl/admin/authserver/clientMan.json" />';
        var api_url_view = '<c:url value="/onl/apim/apigroup/apiGroupMan.view" />';
        var group_url_view = '<c:url value="/onl/admin/authserver/clientMan.view" />';

        var isDetail = false;

        function isValid() {
            if ($('input[name=clientName]').val() == "") {
                alert("CLIENT명을 입력하여 주십시요.");
                $('input[name=clientName]').focus();
                return false;
            }
            if ($('input[name=clientId]').val() == "") {
                alert("CLIENT 아이디를 입력하여 주십시요.");
                $('input[name=clientId]').focus();
                return false;
            }
            if ($('input[name=clientSecret]').val() == "") {
                alert("CLIENT 시크릿을 입력하여 주십시요.");
                $('input[name=clientSecret]').focus();
                return false;
            }
            if ($('input[name=scope]').val() == "") {
                alert("SCOPE를 입력하여 주십시요.");
                $('input[name=scope]').focus();
                return false;
            }
            if ($('input[name=grantTypes]').val() == "") {
                alert("GRANT 타입을 입력하여 주십시요.");
                $('input[name=grantTypes]').focus();
                return false;
            }

            if ($('input[name=accessTokenValiditySeconds]').val() != "") {
                if (isNaN(parseInt($('input[name=accessTokenValiditySeconds]').val()))) {
                    alert("Token 유효기간을 숫자로 입력하여 주십시요.");
                    $('input[name=accessTokenValiditySeconds]').select();
                    return false;
                }
            }
            if ($('input[name=refreshTokenValiditySeconds]').val() != "") {
                if (isNaN(parseInt($('input[name=refreshTokenValiditySeconds]').val()))) {
                    alert("리프레시 Token 유효기간을 숫자로 입력하여 주십시요.");
                    $('input[name=refreshTokenValiditySeconds]').select();
                    return false;
                }
            }

            return true;
        }

        function detail(key) {
            if (!isDetail) return;
            $.ajax({
                type: "POST",
                url: url,
                dataType: "json",
                data: {cmd: 'DETAIL', clientId: key},
                success: function (json) {
                    var apiList = json["APILIST"];
                    var gridData = apiList.map(function (api) {
                        return {
                            apiId: api.eaiSvcName,
                            apiDesc: api.eaiSvcDesc
                        };
                    });
                    $("#selectedApiGrid").jqGrid("clearGridData");
                    $("#selectedApiGrid")[0].addJSONData(gridData);

                    var data = json;
                    $("#btn_gen_id").hide();
                    $('input[name=clientId]').css('width', '100%');
                    $('input[name=clientId]').attr('readonly', true);
                    $("#btn_clientId_byte").hide();
                    $("#btn_gen_secret").hide();
                    $('input[name=clientSecret]').css('width', '100%');
                    $('input[name=clientSecret]').attr('readonly', true);
                    $("#btn_clientSecret_byte").hide();

                    $("#ajaxForm input[type!=checkbox],#ajaxForm select,#ajaxForm textarea").each(function () {
                        var name = $(this).attr("name");
                        var tag = $(this).prop("tagName").toLowerCase();
                        $(tag + "[name=" + name + "]").val(data[name.toUpperCase()]);
                    });

                    // Set the appStatus dropdown value
                    if (json.APPSTATUS !== undefined && json.APPSTATUS !== null) {
                        $('select[name=appStatus]').val(json.APPSTATUS);
                    } else {
                        $('select[name=appStatus]').val('1'); // Set to normal if no value
                    }

                    // 구분자(,) 포함 strings --> checkbox checked
                    var grantTypes = $('input[name=grantTypes]').val();
                    if (grantTypes != "") {
                        var grantTypeArr = grantTypes.split(",");
                        var $checkboxes = $("input[name=grantTypes_]");
                        $checkboxes.each(function (idx, element) {
                            if (grantTypeArr.indexOf(element.value) != -1) {
                                element.setAttribute("checked", "checked");
                            } else {
                                element.removeAttribute("checked");
                            }
                        });
                    }
                },
                error: function (e) {
                    alert(e.responseText);
                }
            });
        }

        function init(key, callback) {

            var selectedApiGrid = $("#selectedApiGrid");
            selectedApiGrid.jqGrid({
                datatype: "local",
				gridview: true, // 성능 향상
				rownumbers: true, // 가상 인덱스
                rownumWidth: 40,
                colNames: ['API ID', 'API 이름'],
                colModel: [
                    {name: 'apiId', index: 'apiId', width: 100, align: 'center'},
                    {name: 'apiDesc', index: 'apiDesc', width: 100, align: 'center'}
                ],
                rowNum: -1,
//                 rowList: [10, 20, 30],
//                 pager: '#selectedApiGridPager',
//                 sortname: 'apiId',
                viewrecords: true,
//                 sortorder: "asc",
                caption: "선택된 API",
                height: 200,
                autowidth: true,
                multiselect: true,
                ondblClickRow: function (rowid, status, e) {
                    // selectedApiGrid.jqGrid('delRowData', rowid);
                }
            });

            selectedApiGrid.jqGrid('setLabel', 'rn', 'No'); // 가상 인덱스 ColNames 
            
            $.ajax({
                type: "POST",
                url: url,
                dataType: "json",
                data: {cmd: 'LIST_DETAIL_COMBO'},
                success: function (json) {
                    json.portalOrgList.unshift({
                        id: "",  // 실제 저장될 값은 빈 문자열
                        orgName: "미분류"  // 화면에 표시될 텍스트
                    });
                    new makeOptions("id", "orgName")
                        .setObj($("select[name=orgId]"))
                        .setFormat(nameOptionFormat)
                        .setData(json.portalOrgList).rendering();
                    if(key) {
                        detail(key);
                    }
                },
                error: function (e) {
                    alert(e.responseText);
                }
            });

            callback(key);
        }

        $(document).ready(function () {
            var returnUrl = getReturnUrlForReturn();
            var key = "${param.clientId}";
            if (key != "" && key != "null") {
                isDetail = true;
            }
            init(key, detail);

            $("#btn_modify").click(function () {
                // checkbox checked --> 구분자(,) 포함 strings
                var selected = new Array();
                $("input[name=grantTypes_]:checked").each(function () {
                    selected.push(this.value);
                });
                if (selected.length > 0) {
                    $('input[name=grantTypes]').val(selected.join(","));
                }

                if (!isValid()) {
                    return;
                }
                var postData = $('#ajaxForm').serializeArray();
                if (isDetail) {
                    postData.push({name: "cmd", value: "UPDATE"});
                } else {
                    postData.push({name: "cmd", value: "INSERT"});
                }

                var data = $("#selectedApiGrid").getRowData();
                var gridData = [];
                for (var i = 0; i < data.length; i++) {
                    gridData.push({eaiSvcName: data[i]['apiId']});
                }

                const orgName = $("select[name=orgId] option:selected").text();
                postData.push({
                    name: "orgName",
                    value: orgName
                });

                postData.push({
                    name: "apiList",
                    value: JSON.stringify(gridData)
                });

                $.ajax({
                    type: "POST",
                    url: url,
                    data: postData,
                    success: function (args) {
                        alert("저장 되었습니다.");
                        goNav(returnUrl);//LIST로 이동
                    },
                    error: function (e) {
                        alert(e.responseText);
                    }
                });
            });

            $("#btn_delete").click(function () {
                if (confirm("삭제하시겠습니까?")) {
                    var clientId = $("#clientId").val();

                    // mTLS 인증서 존재여부 체크
                    $.ajax({
                        type: "POST",
                        url: url,
                        data: { cmd: 'CHECKMTLS', clientId: clientId   },
                        success: function (response) {
                            if (response.hasMtls) {
                                alert("해당 Client 아이디로 등록된 인증서 정보가 있습니다.\n인증서 정보를 먼저 삭제해 주십시오.");
                                return;
                            }

                            // 인증서 없으면 삭제진행
                            $.ajax({
                                type: "POST",
                                url: url,
                                data: { cmd: 'DELETE', clientId: clientId   },
                                success: function (args) {
                                    if (args.status === "error") {
                                        alert("동기화중 오류입니다.\n확인하여 주십시요.\n" + args.message);
                                    } else {
                                        alert("삭제 되었습니다.");
                                        goNav(returnUrl);//LIST로 이동
                                    }
                                },
                                error: function (e) {
                                    alert(e.responseText);
                                }
                            });

                        },
                        error: function (e) {
                            alert(e.responseText);
                        }
                    });

                }
            });

            $("#btn_sync_portal").click(function() {
                var clientId = $('input[name=clientId]').val();
                var clientName = $('input[name=clientName]').val();

                if (!clientId) {
                    alert("Client ID가 없습니다.");
                    return;
                }

                if (!confirm("'" + clientName + "'의 개발자포탈 정보를 반영하시겠습니까?\n\n" +
                             "APIGW 인증 정보를 포탈 DB에 반영합니다. (없으면 생성, 있으면 업데이트)")) {
                    return;
                }

                $.ajax({
                    type: "POST",
                    url: url,
                    dataType: "json",
                    data: {
                        cmd: 'SYNC_PORTAL',
                        clientId: clientId
                    },
                    success: function(response) {
                        showSyncResultModal(response);
                    },
                    error: function(xhr) {
                        alert("반영 중 오류가 발생했습니다.");
                    }
                });
            });

            $("#btn_popup_api").click(function () {
                const args = {};
                const url2 = api_url_view += "?cmd=POPUP";
                showModal(url2, args, 1280, 860, function () {
                    const popupFrame = args.self.frames[0];
                    const returnValue = popupFrame.returnValue;
                    const frameElement = popupFrame.frameElement
                    const parentElement = frameElement.parentNode; // 부모 노드를 가져옴

                    if (parentElement) { // 부모 노드가 존재하는지 확인
                        parentElement.removeChild(frameElement);
                    }

                    var rows = $("#selectedApiGrid").jqGrid('getRowData');

                    var existingApiIds = new Set(rows.map(function(row) {
                        return String(row.apiId);
                    }));

                    var newItems = Array.isArray(returnValue) ? returnValue : [returnValue];

                    var ids = $("#selectedApiGrid").jqGrid('getDataIDs');
                    var currentIdSeq = ids.length > 0 ? Math.max(...ids.map(Number)) : 0;

                    $.each(newItems, function(index, item) {
                        var checkId = String(item.apiId); 
                        
                        if (!existingApiIds.has(checkId)) {
                            currentIdSeq++; 
                            $("#selectedApiGrid").jqGrid('addRowData', currentIdSeq, item, "last");
                            
                            existingApiIds.add(checkId); 
                        } else {
                            //console.log("중복 제외됨: " + item.apiId);
                        }
                    });
                alert("중복건 수를 제외한 API가 추가되었습니다.");
	            });
            });

            $("#btn_popup_api_group").click(function () {
                const args = {};
                const url2 = group_url_view += "?cmd=GROUP_POPUP";
                showModal(url2, args, 1280, 860, function () {
                    const popupFrame = args.self.frames[0];
                    const returnValue = popupFrame.returnValue;
                    const frameElement = popupFrame.frameElement
                    const parentElement = frameElement.parentNode; // 부모 노드를 가져옴

                    if (parentElement) { // 부모 노드가 존재하는지 확인
                        parentElement.removeChild(frameElement);
                    }

                    var rows = $("#selectedApiGrid").jqGrid('getRowData');
                    console.log(returnValue);
                    if (!returnValue.apiGroupApiList || returnValue.apiGroupApiList.length === 0) {
                        return; // If apiGroupApiList is empty, do nothing
                    }

                    returnValue.apiGroupApiList.forEach(function (apiGroupApi) {
                        const apiId = apiGroupApi.apiId;
                        var apiIdExists = rows.some(function (row) {
                            return row.apiId === apiId;
                        });

                        if (apiIdExists) {
                            return;
                        }

                        var ids = $("#selectedApiGrid").jqGrid('getDataIDs');
                        var lastId = ids.length > 0 ? Math.max.apply(Math, ids) : 0;
                        var newId = lastId + 1;
                        $("#selectedApiGrid").jqGrid('addRowData', newId, apiGroupApi, "last");
                    });
                });
            });

            $("#btn_delete_api").click(function () {
                var grid = $("#selectedApiGrid");
                var selectedRowIds = grid.jqGrid('getGridParam', 'selarrrow'); // 선택된 행의 ID 배열을 가져옴
                if (selectedRowIds.length > 0) {
                    // 선택된 행의 ID를 복사한 배열을 사용
                    var idsToDelete = selectedRowIds.slice();

                    for (var i = 0; i < idsToDelete.length; i++) {
                        grid.jqGrid('delRowData', idsToDelete[i]); // 선택된 각 행을 삭제
                    }
                } else {
                    alert("Please select at least one row to delete.");
                }
            });

            $("#btn_previous").click(function () {
                goNav(returnUrl);//LIST로 이동
            });

            $("#btn_gen_id").click(function () {
                //$('input[name=clientId]').val(generateString(32));
                $('input[name=clientId]').val(generateString($("#btn_clientId_byte").val()));
            });

            $("#btn_gen_secret").click(function () {
                //$('input[name=clientSecret]').val(generateString(128));
                $('input[name=clientSecret]').val(generateString($("#btn_clientSecret_byte").val()));
            });

            buttonControl(isDetail);
            titleControl(isDetail);
        });

        const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

        function generateString(length) {
            let result = '';
            const charactersLength = characters.length;
            const randomValues = new Uint32Array(length);
            window.crypto.getRandomValues(randomValues);
            for (let i = 0; i < length; i++) {
                result += characters.charAt(randomValues[i] % charactersLength);
            }
            return result;
        }

    </script>
</head>
<body>
<div class="right_box">
    <div class="content_top">
        <ul class="path">
            <li><a href="#">${rmsMenuPath}</a></li>
        </ul>
    </div><!-- end content_top -->
    <div class="content_middle">
        <div class="search_wrap">
            <button type="button" class="cssbtn" id="btn_sync_portal" level="W" status="DETAIL"><i class="material-icons">sync</i> 개발자포탈 정보 반영
            </button>
            <button type="button" class="cssbtn" id="btn_delete" level="W" status="DETAIL"><i class="material-icons">delete</i> <%= localeMessage.getString("button.delete") %>
            </button>
            <button type="button" class="cssbtn" id="btn_modify" level="W" status="DETAIL,NEW"><i
                    class="material-icons">save</i> <%= localeMessage.getString("button.modify") %>
            </button>
            <button type="button" class="cssbtn" id="btn_previous" level="R" status="DETAIL,NEW"><i
                    class="material-icons">arrow_back</i> <%= localeMessage.getString("button.previous") %>
            </button>
            <%-- 					<img src="<c:url value="/img/btn_delete.png"/>" alt="" id="btn_delete" level="W" status="DETAIL"/> --%>
            <%-- 					<img src="<c:url value="/img/btn_modify.png"/>" alt="" id="btn_modify" level="W" status="DETAIL,NEW" /> --%>
            <%-- 					<img src="<c:url value="/img/btn_previous.png"/>" alt="" id="btn_previous" level="R" status="DETAIL,NEW"/> --%>
        </div>
        <div class="title" id="title">${rmsMenuName}</div>

        <form id="ajaxForm">
            <table class="table_row" cellspacing="0">
                <tr>
                    <th style="width:180px;"><%= localeMessage.getString("clntManDtl.clntNm") %> <small>(*)</small></th>
                    <td><input type="text" name="clientName"/></td>
                </tr>
                <tr>
                    <th><%= localeMessage.getString("clntManDtl.clntId") %> <small>(*)</small></th>
                    <td>
                        <!--  <input type="text" name="clientId" readonly="readonly" style="width: calc(100% - 62px);"/>	-->
                        <input type="text" name="clientId" id ="clientId" style="width: calc(100% - 142px);"/>
                        <select name="clientId_byte" id="btn_clientId_byte" style="width: 76px;">
                            <option value="32" selected="selected">32 byte</option>
                            <option value="64">64 byte</option>
                            <option value="128">128 byte</option>
                            <option value="256">256 byte</option>
                        </select>
                        <img src="<c:url value="/img/btn_pop_input.png"/>" id="btn_gen_id"/>
                    </td>
                </tr>
                <tr>
                    <th><%= localeMessage.getString("clntManDtl.clntScrt") %> <small>(*)</small></th>
                    <td>
                        <!--  <input type="text" name="clientSecret" readonly="readonly" style="width: calc(100% - 62px);"/>	-->
                        <input type="text" name="clientSecret" style="width: calc(100% - 142px);"/>
                        <select name="clientSecret_byte" id="btn_clientSecret_byte" style="width: 76px;">
                            <option value="32">32 byte</option>
                            <option value="64">64 byte</option>
                            <option value="128" selected="selected">128 byte</option>
                            <option value="256">256 byte</option>
                        </select>
                        <img src="<c:url value="/img/btn_pop_input.png"/>" id="btn_gen_secret"/>
                    </td>
                </tr>
                <tr>
                    <th>SCOPE(<%= localeMessage.getString("clntManDtl.sprt") %> ,) <small>(*)</small></th>
                    <td><input type="text" name="scope"/></td>
                </tr>
                <tr>
                    <th><%= localeMessage.getString("clntManDtl.grntTp") %>
                        (<%= localeMessage.getString("clntManDtl.sprt") %> ,) <small>(*)</small></th>
                    <td>
                        <input type="checkbox" name="grantTypes_" value="client_credentials"> client_credentials
                        <%--								<input type="checkbox" name="grantTypes_" value="authorization_code"> authorization_code--%>
                        <%--								<input type="checkbox" name="grantTypes_" value="password"> password--%>
                        <input type="checkbox" name="grantTypes_" value="refresh_token"> refresh_token
                    </td>
                    <input type="hidden" name="grantTypes"/>
                    </td>
                </tr>
                <tr>
                    <th>REDIRECT URI</th>
                    <td><input type="text" name="redirectUri"/></td>
                </tr>
                <tr style="display: none;">
                    <th><%= localeMessage.getString("clntManDtl.athrt") %>
                        (<%= localeMessage.getString("clntManDtl.sprt") %> ,)
                    </th>
                    <td><input type="text" name="authorities" value=""/></td>
                </tr>
                <tr style="display: none;">
                    <th><%= localeMessage.getString("clntManDtl.rsrc") %>
                        (<%= localeMessage.getString("clntManDtl.sprt") %> ,)
                    </th>
                    <td><input type="text" name="resourceIds" value=""/></td>
                </tr>
                <tr>
                    <th><%= localeMessage.getString("clntManDtl.tknExprtnDt") %>
                    </th>
                    <td><input type="text" name="accessTokenValiditySeconds"/></td>
                </tr>
                <tr>
                    <th><%= localeMessage.getString("clntManDtl.rfrshTknExprtnDt") %>
                    </th>
                    <td><input type="text" name="refreshTokenValiditySeconds"/></td>
                </tr>
                <tr style="display: none;">
                    <th><%= localeMessage.getString("clntManDtl.atmtcApprvlScp") %>
                        (<%= localeMessage.getString("clntManDtl.sprt") %> ,)
                    </th>
                    <td><input type="text" name="autoApprove" value=""/></td>
                </tr>
                <tr>
                    <th><%= localeMessage.getString("clntManDtl.allwIp") %>
                        (<%= localeMessage.getString("clntManDtl.sprt") %> ,)
                    </th>
                    <td><input type="text" name="allowedIps"/></td>
                </tr>
                <tr>
                    <th>Security Key</th>
                    <td><textarea name="securityKey" rows="3" style="width:100%;"></textarea></td>
                </tr>
                <tr>
                    <th>APP 상태</th>
                    <td>
                        <div class="select-style">
                            <select name="appStatus">
                                <option value="1" selected>정상</option>
                                <option value="0">차단</option>
                            </select>
                        </div>
                    </td>
                </tr>
                <tr>
                    <th>법인</th>
                    <td>
                        <div class="select-style">
                            <select id="orgId" class="form-control" name="orgId">
                            </select>
                        </div>
                    </td>
                </tr>
                <tr style="display: none;">
                    <th>토큰 발급 제한건수(24시간)</th>
                    <td>
                        <div class="select-style">
                            <input type="text" name="dailyTokenLimit" value=0></input>
                        </div>
                    </td>
                </tr>
            </table>
        </form>
        <div style="font-size:0;">
            <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 5px ">
                <div class="table_row_title" style="margin-bottom: 0px">API</div>
                <div style="text-align: end;">
                    <button type="button" class="cssbtn" id="btn_delete_api" level="W" status="DETAIL,NEW">
                        <i class="material-icons">delete</i> <%= localeMessage.getString("button.delete") %>
                    </button>
                    <button type="button" class="cssbtn" id="btn_popup_api" level="W" status="DETAIL,NEW">
                        <i class="material-icons">add</i> API <%= localeMessage.getString("button.add") %>
                    </button>
                    <button type="button" class="cssbtn" id="btn_popup_api_group" level="W" status="DETAIL,NEW">
                        <i class="material-icons">add</i> API 그룹<%= localeMessage.getString("button.add") %>
                    </button>
                </div>
            </div>
            <div style="display:inline-block; width:calc(100%); vertical-align:top;">
                <div id="selectedApiList" style="margin-top:10px;">
                    <table id="selectedApiGrid"></table>
                </div>
            </div>
        </div>
    </div><!-- end content_middle -->
</div><!-- end right_box -->

<!-- 포탈 반영 결과 Modal -->
<div id="syncResultModal" class="modal-overlay" style="display:none;">
    <div class="modal-content" style="width:700px; max-height:80vh; overflow-y:auto;">
        <div class="modal-header">
            <h3 id="syncResultTitle">개발자포탈 반영 결과</h3>
            <button type="button" class="modal-close" onclick="closeSyncResultModal()">&times;</button>
        </div>
        <div class="modal-body">
            <div id="syncResultStatus" style="padding:15px; margin-bottom:15px; border-radius:4px;"></div>

            <div id="syncResultApiSection">
                <h4 style="margin:10px 0;">반영 대상 API 목록 (<span id="targetApiCount">0</span>건)</h4>
                <table class="table_row" cellspacing="0" style="width:100%;">
                    <thead>
                        <tr>
                            <th style="width:50px;">No</th>
                            <th><%= localeMessage.getString("eaiMessage.eaiSvcName")%></th>
                            <th style="width:120px;">상태</th>
                        </tr>
                    </thead>
                    <tbody id="syncResultApiList">
                    </tbody>
                </table>
            </div>
        </div>
        <div class="modal-footer" style="text-align:center; padding:15px;">
            <button type="button" class="cssbtn" onclick="closeSyncResultModal()">
                <i class="material-icons">close</i> 닫기
            </button>
        </div>
    </div>
</div>

<style>
.modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
    z-index: 9999;
    display: flex;
    justify-content: center;
    align-items: center;
}
.modal-content {
    background: white;
    border-radius: 8px;
    box-shadow: 0 4px 20px rgba(0,0,0,0.3);
}
.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    border-bottom: 1px solid #ddd;
    background: #f5f5f5;
    border-radius: 8px 8px 0 0;
}
.modal-header h3 {
    margin: 0;
    font-size: 16px;
}
.modal-close {
    background: none;
    border: none;
    font-size: 24px;
    cursor: pointer;
    color: #666;
}
.modal-close:hover {
    color: #333;
}
.modal-body {
    padding: 20px;
}
.modal-footer {
    border-top: 1px solid #ddd;
}
.status-success {
    background-color: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}
.status-fail {
    background-color: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}
.status-warning {
    background-color: #fff3cd;
    color: #856404;
    border: 1px solid #ffeeba;
}
.api-synced {
    color: #28a745;
    font-weight: bold;
}
.api-invalid {
    color: #dc3545;
    font-weight: bold;
}
.api-created {
    color: #007bff;
    font-weight: bold;
}
</style>

<script>
function closeSyncResultModal() {
    $("#syncResultModal").hide();
}

function showSyncResultModal(response) {
    var $modal = $("#syncResultModal");
    var $status = $("#syncResultStatus");
    var $apiList = $("#syncResultApiList");
    var $targetCount = $("#targetApiCount");

    // 상태 메시지
    var statusClass = "";
    var statusMsg = "";

    if (response.success) {
        statusClass = "status-success";
        var createdCount = response.createdApiSpecCount || 0;
        var createdMsg = createdCount > 0 ? "<br/><span style='color:#007bff;'>* " + createdCount + "개의 API Spec이 자동 생성되었습니다.</span>" : "";

        if (response.action === 'INSERTED') {
            statusMsg = "<strong>반영 완료</strong> - 포탈에 새로운 인증정보가 생성되었습니다." + createdMsg;
        } else if (response.action === 'UPDATED') {
            statusMsg = "<strong>반영 완료</strong> - 기존 포탈 인증정보가 업데이트되었습니다." + createdMsg;
        } else {
            statusMsg = "<strong>반영 완료</strong> - " + response.message + createdMsg;
        }
    } else {
        if (response.action === 'SKIPPED_NO_ORG') {
            statusClass = "status-warning";
            statusMsg = "<strong>반영 건너뜀</strong> - 법인(orgId)이 설정되지 않은 클라이언트입니다.";
        } else if (response.action === 'SKIPPED_INVALID_API') {
            statusClass = "status-fail";
            statusMsg = "<strong>반영 실패</strong> - 존재하지 않는 API가 포함되어 있어 반영을 중단합니다.";
        } else {
            statusClass = "status-fail";
            statusMsg = "<strong>반영 실패</strong> - " + response.message;
        }
    }

    $status.removeClass("status-success status-fail status-warning").addClass(statusClass).html(statusMsg);

    // API 목록 표시
    $apiList.empty();
    var targetApis = response.targetApis || [];
    var syncedApis = response.syncedApis || [];
    var invalidApis = response.invalidApis || [];
    var createdApiSpecs = response.createdApiSpecs || [];

    $targetCount.text(targetApis.length);

    if (targetApis.length === 0) {
        $apiList.append('<tr><td colspan="3" style="text-align:center;">등록된 API가 없습니다.</td></tr>');
    } else {
        targetApis.forEach(function(apiId, index) {
            var status = "";
            var statusClass = "";

            if (invalidApis.includes(apiId)) {
                status = "미존재 (APIGW에 없음)";
                statusClass = "api-invalid";
            } else if (createdApiSpecs.includes(apiId)) {
                status = "반영됨 (Spec 신규생성)";
                statusClass = "api-created";
            } else if (syncedApis.includes(apiId)) {
                status = "반영됨";
                statusClass = "api-synced";
            } else if (response.success) {
                status = "반영됨";
                statusClass = "api-synced";
            } else {
                status = "미반영";
                statusClass = "";
            }

            $apiList.append(
                '<tr>' +
                '<td style="text-align:center;">' + (index + 1) + '</td>' +
                '<td>' + apiId + '</td>' +
                '<td class="' + statusClass + '" style="text-align:center;">' + status + '</td>' +
                '</tr>'
            );
        });
    }

    $modal.show();
}
</script>

</body>
</html>
