// src/cmsService.js
// Ghost CMS Admin API integration for member management

const api = require('@tryghost/admin-api');

const cms = new api({
    url: process.env.CMS_URL,
    key: process.env.CMS_ADMIN_KEY,
    version: 'v5.0'
});

/**
 * Find a Ghost member by their email address
 * @param {string} email - Email address to search for
 * @returns {Promise<Object>} - Ghost member object
 * @throws {Error} - If member not found
 */
async function findMemberByEmail(email) {
    // We use the browse method with a filter to find the exact match
    const members = await cms.members.browse({ filter: `email:'${email}'` });
    
    if (members.length === 0) {
        throw new Error('Member not found');
    }
    
    // Return the first match
    return members[0]; 
}

/**
 * Update a Ghost member's discord_id custom field
 * @param {string} email - Member's email address
 * @param {string} discordId - Discord user ID (snowflake)
 * @returns {Promise<Object>} - Updated member object
 */
async function updateMemberDiscordId(email, discordId) {
    const members = await cms.members.browse({ filter: `email:'${email}'` });
    
    if (members.length === 0) {
        throw new Error('Member not found in CMS');
    }

    const updated = await cms.members.edit({
        id: members[0].id,
        custom_fields: [
            { name: 'discord_id', value: discordId }
        ]
    });
    
    console.log(`[Ghost] Updated discord_id for ${email}`);
    return updated;
}

module.exports = { 
    findMemberByEmail, 
    updateMemberDiscordId 
};
