import type { Expense, ExpenseTotals } from "src/modules/timesheets/models/expense.models";

//------------------ normalization / icons ------------------
export const normExpenseType = (type: unknown): string => 
    typeof type === 'string' ? type.trim().toUpperCase() : '';

const icon_map: Record<string,string> = {
    MILEAGE:     'time_to_leave',
    EXPENSES:    'receipt_long',
    PER_DIEM:    'hotel',
    PRIME_GARDE: 'admin_panel_settings',
};

export const expenseTypeIcon = (type: unknown): string => {
    const t = normExpenseType(type);
    return (
        icon_map[t.toLowerCase()] ??
        icon_map[t.replace('-','_').toLowerCase()] ??
        'help_outline'
    );
};

//------------------ totals ------------------
export const computeExpenseTotals = (items: readonly Expense[]): ExpenseTotals =>
    items.reduce<ExpenseTotals>(
        (acc, e) => ({
            amount:  acc.amount  + (Number(e.amount)  || 0),
            mileage: acc.mileage + (Number(e.mileage) || 0),
        }),
        { amount: 0, mileage: 0 }
);

//------------------ Quasar :rules=[] ------------------
export const makeExpenseRules = (t: (_key: string) => string) => {
    const isPresent = (val: unknown) => val !== undefined && val !== null && val !== '';

    const typeRequired    = (val: unknown) => (!!val)                               || t('timesheet.expense.errors.type_required');

    const amountRequired  = (val: unknown) => (isPresent(val))                      || t('timesheet.expense.errors.amount_required_for_type');

    const mileageRequired = (val: unknown) => (isPresent(val))                      || t('timesheet.expense.errors.mileage_required_for_type');
    
    const commentRequired = (val: unknown) => (typeof val === 'string' ? val.trim().length > 0 : false ) || t('timesheet.expense.errors.comment_required');

    return {
        typeRequired,
        amountRequired,
        mileageRequired,
        commentRequired,
    };
};