import { CHECKMARK, parseBooleanValue, PROPERTY_HEADERS } from '../domain/types.js';
import { propertyToSheetRow, sheetRowToProperty } from './property-transformer.js';
const PIVOT_SEPARATOR = '\u2550\u2550\u2550\u2550\u2550\u2550';
export function createPivotSeparator(pivotName) {
    const separator = `${PIVOT_SEPARATOR} PIVOT: ${pivotName} ${PIVOT_SEPARATOR}`;
    const row = Array.from({ length: PROPERTY_HEADERS.length }).fill('');
    row[0] = separator;
    return row;
}
export function isPivotSeparator(row) {
    return row[0]?.includes(PIVOT_SEPARATOR) && row[0]?.includes('PIVOT:');
}
export function extractPivotNameFromSeparator(row) {
    if (!isPivotSeparator(row))
        return null;
    const match = row[0].match(/PIVOT:\s*([^\s\u2550]+)/);
    return match ? match[1] : null;
}
export function createPivotMetadataRows(pivot) {
    const rows = [];
    const emptyPadding = Array.from({ length: PROPERTY_HEADERS.length - 2 }).fill('');
    rows.push(['Bounded Context', pivot.boundedContextName, ...emptyPadding], ['Module Name', pivot.moduleName, ...emptyPadding], ['Module Names', pivot.moduleNames, ...emptyPadding], ['Aggregate Name', pivot.aggregateName, ...emptyPadding], ['Has OAuth', pivot.hasOAuth ? CHECKMARK : '', ...emptyPadding], ['Has Tenant', pivot.hasTenant ? CHECKMARK : '', ...emptyPadding], [
        'Has Auditing',
        pivot.hasAuditing ? CHECKMARK : '',
        ...emptyPadding,
    ]);
    return rows;
}
export function parsePivotMetadataRows(rows) {
    const metadata = {};
    for (const row of rows) {
        const label = row[0]?.trim();
        const value = row[1]?.trim();
        switch (label) {
            case 'Aggregate Name': {
                metadata.aggregateName = value;
                break;
            }
            case 'Bounded Context': {
                metadata.boundedContextName = value;
                break;
            }
            case 'Has Auditing': {
                metadata.hasAuditing = parseBooleanValue(value);
                break;
            }
            case 'Has OAuth': {
                metadata.hasOAuth = parseBooleanValue(value);
                break;
            }
            case 'Has Tenant': {
                metadata.hasTenant = parseBooleanValue(value);
                break;
            }
            case 'Module Name': {
                metadata.moduleName = value;
                break;
            }
            case 'Module Names': {
                metadata.moduleNames = value;
                break;
            }
        }
    }
    return metadata;
}
/**
 * Converts a pivot to sheet rows: separator + metadata + header + properties.
 */
export function pivotToSheetRows(pivot) {
    const emptyRow = Array.from({ length: PROPERTY_HEADERS.length }).fill('');
    const rows = [
        createPivotSeparator(pivot.moduleName),
        emptyRow,
        ...createPivotMetadataRows(pivot),
        [...emptyRow],
        PROPERTY_HEADERS,
    ];
    for (const prop of pivot.aggregateProperties || []) {
        const propRow = propertyToSheetRow(prop);
        const values = PROPERTY_HEADERS.map((header) => propRow[header] || '');
        rows.push(values);
    }
    return rows;
}
export function parsePivotFromSheetRows(rows) {
    if (rows.length === 0)
        return null;
    const separatorIdx = rows.findIndex((row) => isPivotSeparator(row));
    if (separatorIdx === -1)
        return null;
    const pivotName = extractPivotNameFromSeparator(rows[separatorIdx]);
    if (!pivotName)
        return null;
    const metadataRows = [];
    let headerIdx = -1;
    for (let i = separatorIdx + 1; i < rows.length; i++) {
        const row = rows[i];
        if (row[0] === 'name' && row[1] === 'type') {
            headerIdx = i;
            break;
        }
        if (row[0]?.trim()) {
            metadataRows.push(row);
        }
    }
    if (headerIdx === -1)
        return null;
    const metadata = parsePivotMetadataRows(metadataRows);
    const properties = [];
    const headers = rows[headerIdx];
    for (let i = headerIdx + 1; i < rows.length; i++) {
        const row = rows[i];
        if (!row[0]?.trim() || isPivotSeparator(row))
            break;
        const propObj = {};
        for (const [j, header] of headers.entries()) {
            propObj[header] = row[j] || '';
        }
        properties.push(sheetRowToProperty(propObj));
    }
    return {
        metadata: {
            aggregateName: metadata.aggregateName || '',
            boundedContextName: metadata.boundedContextName || '',
            hasAuditing: metadata.hasAuditing ? 'TRUE' : 'FALSE',
            hasOAuth: metadata.hasOAuth ? 'TRUE' : 'FALSE',
            hasTenant: metadata.hasTenant ? 'TRUE' : 'FALSE',
            moduleName: metadata.moduleName || pivotName,
            moduleNames: metadata.moduleNames || '',
        },
        pivotName,
        properties: properties.map((p) => propertyToSheetRow(p)),
    };
}
export function sheetPivotDataToPivot(data) {
    return {
        aggregateName: data.metadata.aggregateName,
        aggregateProperties: data.properties.map((p) => sheetRowToProperty(p)),
        boundedContextName: data.metadata.boundedContextName,
        hasAuditing: parseBooleanValue(data.metadata.hasAuditing),
        hasOAuth: parseBooleanValue(data.metadata.hasOAuth),
        hasTenant: parseBooleanValue(data.metadata.hasTenant),
        moduleName: data.metadata.moduleName,
        moduleNames: data.metadata.moduleNames,
    };
}
export function findAllPivotSections(rows) {
    const sections = [];
    for (const [i, row] of rows.entries()) {
        if (isPivotSeparator(row)) {
            const name = extractPivotNameFromSeparator(row);
            if (name) {
                sections.push({ name, startIdx: i });
            }
        }
    }
    return sections;
}
