/*
 * cl_streak_cursor_dbio.pgc - cl 모듈 DB 접근 함수 (cl_streak_cursor_dbio), archived into libcldbio.a.
 * 일마감 연속 완료 최장 구간 (cursor + 상태 누적).
 * ECPG (EXEC SQL) functions; run on the caller's XA branch. No EXEC SQL CONNECT.
 */
#include <string.h>
#include <userlog.h>
#include "cl_streak_cursor_dbio.h"

/* 날짜순 DAILY 마감을 훑어 status='C' 연속 최장 구간 길이 반환. */
long clqdb_close_streak(const char *prefix)
{
    EXEC SQL BEGIN DECLARE SECTION;
    char h_prefix[16], h_status[4];
    EXEC SQL END DECLARE SECTION;
    long cur = 0, best = 0;
    strncpy(h_prefix, prefix, sizeof(h_prefix)-1); h_prefix[sizeof(h_prefix)-1] = 0;
    EXEC SQL DECLARE csk CURSOR FOR
        SELECT status FROM cl_close_log
        WHERE close_type = 'DAILY' AND period_key LIKE :h_prefix || '%'
        ORDER BY biz_date;
    EXEC SQL OPEN csk;
    if (sqlca.sqlcode < 0) return -1;
    for (;;) {
        EXEC SQL FETCH csk INTO :h_status;
        if (sqlca.sqlcode == 100) break;
        if (sqlca.sqlcode < 0) { EXEC SQL CLOSE csk; return -1; }
        if (h_status[0] == 'C') { cur++; if (cur > best) best = cur; }
        else cur = 0;
    }
    EXEC SQL CLOSE csk;
    return best;
}
