// Utility to parse and stringify Bacula Config Resources
// Format:
// ResourceType {
//   Key = Value
//   Key = "Value With Spaces"
// }

const parseConfig = (content) => {
    const lines = content.split('\n');
    const resources = [];
    let currentResource = null;

    lines.forEach(line => {
        const trimmed = line.trim();
        if (!trimmed || trimmed.startsWith('#')) return;

        // Start of Resource
        if (trimmed.match(/^[a-zA-Z0-9]+\s*{/)) {
            const type = trimmed.split(/\s+/)[0];
            currentResource = { _type: type };
        }
        // End of Resource
        else if (trimmed === '}') {
            if (currentResource) {
                resources.push(currentResource);
                currentResource = null;
            }
        }
        // Key-Value Pair
        else if (currentResource && trimmed.includes('=')) {
            const [key, ...values] = trimmed.split('=');
            let value = values.join('=').trim();

            // Remove wrapping quotes and trailing semicolons
            value = value.replace(/^"|"$/g, '').replace(/;$/, '');

            currentResource[key.trim()] = value;
        }
    });

    return resources;
};

const generateClientConfig = (data) => {
    return `Client {
  Name = "${data.Name}"
  Address = "${data.Address}"
  FDPort = ${data.FDPort || 9102}
  Catalog = "${data.Catalog || 'MyCatalog'}"
  Password = "${data.Password}"
  File Retention = ${data.FileRetention || '30 days'}
  Job Retention = ${data.JobRetention || '6 months'}
  AutoPrune = ${data.AutoPrune || 'yes'}
}`;
};

module.exports = { parseConfig, generateClientConfig };
