const moment_timeZone = require('moment-timezone');

function get24HoursTimeFromISO(isoDateTime) {
    const date = new Date(isoDateTime);
    const hh = String(date.getUTCHours()).padStart(2, '0');
    const mm = String(date.getUTCMinutes()).padStart(2, '0');
    const ss = String(date.getUTCSeconds()).padStart(2, '0');
    return `${hh}:${mm}:${ss}`;
}

/**
 * Convert ISO datetime string or Date object to 12-hour IST time format.
 * @param {string|Date} isoDateTime - ISO string or Date object
 * @param {boolean} isSecond - If true, includes seconds
 * @returns {string} - Formatted time string like "04:30 PM" or "04:30:15 PM"
 */
function get12HoursTimeFromISO(isoDateTime, isSecond = false) {
    if (!isoDateTime) return '';

    let istMoment;

    // ✅ Detect if the input is only a time (like "12:30" or "12:30 PM")
    const isOnlyTime = typeof isoDateTime === 'string' && !isoDateTime.includes('T');

    if (isOnlyTime) {
        // Combine with today's date to make it ISO-compatible
        const today = moment_timeZone().tz('Asia/Kolkata').format('YYYY-MM-DD');
        istMoment = moment_timeZone.tz(`${today} ${isoDateTime}`, 'YYYY-MM-DD HH:mm', 'Asia/Kolkata');
    } else {
        // Handle normal ISO or Date input
        istMoment = moment_timeZone(isoDateTime).tz('Asia/Kolkata');
    }

    return istMoment.format(isSecond ? 'hh:mm:ss A' : 'hh:mm A');
}

function getISOFrom12HoursTime(time12HourFormat, dateStr = null) {
    // time12HourFormat example: "05:30 AM" or "05:30:15 PM"
    const [timePart, period] = time12HourFormat.trim().split(' ');

    const timeSegments = timePart.split(':');
    const hourStr = timeSegments[0];
    const minuteStr = timeSegments[1];
    const secondStr = timeSegments[2] || '00';

    let hours = parseInt(hourStr, 10);
    const minutes = parseInt(minuteStr, 10);
    const seconds = parseInt(secondStr, 10);

    if (period.toUpperCase() === 'PM' && hours !== 12) {
        hours += 12;
    } else if (period.toUpperCase() === 'AM' && hours === 12) {
        hours = 0;
    }

    // Construct moment_timeZone datetime in IST
    let dateIST;
    if (dateStr) {
        // Expecting format: DD:MM:YYYY
        const [dd, mm, yyyy] = dateStr.split(':').map(Number);
        dateIST = moment_timeZone.tz({
            year: yyyy,
            month: mm - 1, // moment_timeZone months are 0-indexed
            day: dd,
            hour: hours,
            minute: minutes,
            second: seconds
        }, 'Asia/Kolkata');
    } else {
        const now = moment_timeZone.tz('Asia/Kolkata');
        dateIST = moment_timeZone.tz({
            year: now.year(),
            month: now.month(),
            day: now.date(),
            hour: hours,
            minute: minutes,
            second: seconds
        }, 'Asia/Kolkata');
    }

    return dateIST.toISOString(); // Converts to UTC ISO string
}

// Export all functions
module.exports = {
    get24HoursTimeFromISO,
    get12HoursTimeFromISO,
    getISOFrom12HoursTime
};










// import moment_timeZone from 'moment-timezone';

// export function get24HoursTimeFromISO(isoDateTime) {
//     const date = new Date(isoDateTime);
//     const hh = String(date.getUTCHours()).padStart(2, '0');
//     const mm = String(date.getUTCMinutes()).padStart(2, '0');
//     const ss = String(date.getUTCSeconds()).padStart(2, '0');
//     return `${hh}:${mm}:${ss}`;
// }

// /**
//  * Convert ISO datetime string or Date object to 12-hour IST time format.
//  * @param {string|Date} isoDateTime - ISO string or Date object
//  * @param {boolean} isSecond - If true, includes seconds
//  * @returns {string} - Formatted time string like "04:30 PM" or "04:30:15 PM"
//  */
// // export function get12HoursTimeFromISO(isoDateTime, isSecond = false) {
// //     if (!isoDateTime) return '';

// //     const istMoment = moment_timeZone(isoDateTime).tz('Asia/Kolkata');

// //     return istMoment.format(isSecond ? 'hh:mm:ss A' : 'hh:mm A');
// // }



// export function get12HoursTimeFromISO(isoDateTime, isSecond = false) {
//     if (!isoDateTime) return '';

//     let istMoment;

//     // ✅ Detect if the input is only a time (like "12:30" or "12:30 PM")
//     const isOnlyTime = typeof isoDateTime === 'string' && !isoDateTime.includes('T');

//     if (isOnlyTime) {
//         // Combine with today's date to make it ISO-compatible
//         const today = moment_timeZone().tz('Asia/Kolkata').format('YYYY-MM-DD');
//         istMoment = moment_timeZone.tz(`${today} ${isoDateTime}`, 'YYYY-MM-DD HH:mm', 'Asia/Kolkata');
//     } else {
//         // Handle normal ISO or Date input
//         istMoment = moment_timeZone(isoDateTime).tz('Asia/Kolkata');
//     }

//     return istMoment.format(isSecond ? 'hh:mm:ss A' : 'hh:mm A');
// }


// // export function get12HoursTimeFromISO(isoString) {
// //     try {
// //         // Handle both full ISO strings and time-only strings
// //         let momentObj;
// //         if (isoString.includes('T') || isoString.includes('-')) {
// //             momentObj = moment_timeZone(isoString).tz('Asia/Kolkata');
// //         } else {
// //             // If it's just time, create a date with today's date
// //             momentObj = moment_timeZone(`1970-01-01T${isoString}`).tz('Asia/Kolkata');
// //         }
        
// //         return momentObj.format('hh:mm A');
// //     } catch (error) {
// //         console.error('Error formatting time:', isoString, error);
// //         return '';
// //     }
// // }









// export function getISOFrom12HoursTime(time12HourFormat, dateStr = null) {
//     // time12HourFormat example: "05:30 AM" or "05:30:15 PM"
//     const [timePart, period] = time12HourFormat.trim().split(' ');

//     const timeSegments = timePart.split(':');
//     const hourStr = timeSegments[0];
//     const minuteStr = timeSegments[1];
//     const secondStr = timeSegments[2] || '00';

//     let hours = parseInt(hourStr, 10);
//     const minutes = parseInt(minuteStr, 10);
//     const seconds = parseInt(secondStr, 10);

//     if (period.toUpperCase() === 'PM' && hours !== 12) {
//         hours += 12;
//     } else if (period.toUpperCase() === 'AM' && hours === 12) {
//         hours = 0;
//     }

//     // Construct moment_timeZone datetime in IST
//     let dateIST;
//     if (dateStr) {
//         // Expecting format: DD:MM:YYYY
//         const [dd, mm, yyyy] = dateStr.split(':').map(Number);
//         dateIST = moment_timeZone.tz({
//             year: yyyy,
//             month: mm - 1, // moment_timeZone months are 0-indexed
//             day: dd,
//             hour: hours,
//             minute: minutes,
//             second: seconds
//         }, 'Asia/Kolkata');
//     } else {
//         const now = moment_timeZone.tz('Asia/Kolkata');
//         dateIST = moment_timeZone.tz({
//             year: now.year(),
//             month: now.month(),
//             day: now.date(),
//             hour: hours,
//             minute: minutes,
//             second: seconds
//         }, 'Asia/Kolkata');
//     }

//     return dateIST.toISOString(); // Converts to UTC ISO string
// }
