import { TCompareStatsResult } from './types';

const GENERATED_BY_MD = 'Generated by: generate-components-api';
const SUMMARY_TITLE = 'New missing comments';
const SUMMARY_DESC = "NOTE: It's either a new exported types/props without JSDoc, or it's an existing code from which you deleted the JSDoc comments.";
const getCiStatusMd = (isErr: boolean) => `CI Status: ${isErr ? 'error' : 'ok'}`;
const EMODJI = {
    OK: ':ok:',
    ERR: ':no_entry:',
    WARN: ':warning::ok:',
};

export function formatResultsToMd(result: TCompareStatsResult) {
    const isErr = result.propsNoComment.isIncreased;

    const typesAmount = formatAmountWithDiff({
        prev: result.typesNoComment.prev,
        next: result.typesNoComment.next,
        errIcon: EMODJI.WARN,
    });
    const propsAmount = formatAmountWithDiff({
        prev: result.propsNoComment.prev,
        next: result.propsNoComment.next,
        errIcon: EMODJI.ERR,
    });
    const ciStatus = getCiStatusMd(isErr);
    let detailsMd = '';
    if (result.typesNoComment.newWithNoComment.length > 0 || result.propsNoComment.newWithNoComment.length > 0) {
        detailsMd = [
            '<details>',
            `<summary>${SUMMARY_TITLE}</summary>`,
            '<br>',
            SUMMARY_DESC,
            '',
            '```',
            newWithNoCommentsToMdList('Types', result.typesNoComment.newWithNoComment),
            newWithNoCommentsToMdList('Props', result.propsNoComment.newWithNoComment),
            '```',
            '</details>',
        ].join('\n');
    }
    return [
        [
            `${GENERATED_BY_MD}<br>`,
            `${ciStatus}<br>\n\n`,
            '**Total amount of exported types/props without JSDoc comments**<br>',
        ].join(''),
        '',
        '|         | Amount                    |',
        '|:-------:|:-------------------------:|',
        `|  Types  |       ${typesAmount}      |`,
        `|  Props  |       ${propsAmount}      |`,
        detailsMd,
    ].join('\n');

    function newWithNoCommentsToMdList(label: string, items: string[]) {
        if (items.length > 0) {
            const mdList = items.map((line) => `- ${line}`).join('\n');
            return `${label}:\n${mdList}`;
        }
        return `${label}:\n- <empty>`;
    }
    function formatAmountWithDiff(params: { prev: number | undefined, next: number, errIcon: string }) {
        const { errIcon, prev, next } = params;
        let mdTypesAmountChange = '(no baseline :warning:)';
        if (prev !== undefined) {
            const typesAmountDiff = next - prev;
            let typesAmountSign = '+';
            if (typesAmountDiff < 0) {
                typesAmountSign = '';
            }
            const emodji = typesAmountDiff > 0 ? errIcon : EMODJI.OK;
            mdTypesAmountChange = `(${typesAmountSign}${typesAmountDiff}) ${emodji}`;
        }
        return `${next} ${mdTypesAmountChange}`;
    }
}
