<?php

namespace App\Support;

class OpeningBalanceRules
{
    /**
     * @return array{dr_cr: string, amount: float}|null
     */
    public static function forAccountType(string $accountType, float $balance): ?array
    {
        if (abs($balance) < 0.005) {
            return null;
        }

        $amount = abs($balance);
        $creditNormal = in_array($accountType, ['liability', 'equity', 'income'], true);

        $drCr = $creditNormal
            ? ($balance >= 0 ? 'cr' : 'dr')
            : ($balance >= 0 ? 'dr' : 'cr');

        return ['dr_cr' => $drCr, 'amount' => $amount];
    }

    /**
     * Customer balance: positive = amount owed to company (debit A/R).
     *
     * @return array{dr_cr: string, amount: float}|null
     */
    public static function forCustomer(float $balance): ?array
    {
        if (abs($balance) < 0.005) {
            return null;
        }

        return [
            'dr_cr' => $balance >= 0 ? 'dr' : 'cr',
            'amount' => abs($balance),
        ];
    }

    /**
     * Vendor balance: positive = amount owed to vendor (credit A/P).
     *
     * @return array{dr_cr: string, amount: float}|null
     */
    public static function forVendor(float $balance): ?array
    {
        if (abs($balance) < 0.005) {
            return null;
        }

        return [
            'dr_cr' => $balance >= 0 ? 'cr' : 'dr',
            'amount' => abs($balance),
        ];
    }

    /**
     * Inventory opening value is always a debit to the inventory asset account.
     *
     * @return array{dr_cr: string, amount: float}|null
     */
    public static function forItem(float $amount): ?array
    {
        if ($amount < 0.005) {
            return null;
        }

        return ['dr_cr' => 'dr', 'amount' => $amount];
    }

    /**
     * Opening Balance Equity offset for a balanced journal batch.
     *
     * @return array{dr_cr: string, amount: float}|null
     */
    public static function equityOffset(float $totalDebit, float $totalCredit): ?array
    {
        $diff = round($totalDebit - $totalCredit, 2);

        if (abs($diff) < 0.01) {
            return null;
        }

        return [
            'dr_cr' => $diff > 0 ? 'cr' : 'dr',
            'amount' => abs($diff),
        ];
    }
}
