using PowderCoating.Core.Enums;
using PowderCoating.Core.Interfaces;

namespace PowderCoating.Web.Helpers;

/// <summary>
/// Server-side validation for account selections that must be a "money" account — a payment
/// source (bill payment), deposit target, or reconcilable account. The dropdowns already limit
/// the choices, so this is defense in depth against tampered or stale POSTs (e.g. an account
/// deleted/retyped between page load and submit): it rejects anything that isn't an active,
/// company-owned Asset or Liability account before a GL posting is made against it.
/// </summary>
internal static class AccountGuard
{
    /// <summary>
    /// Returns true when <paramref name="accountId"/> identifies an active account belonging to
    /// <paramref name="companyId"/> whose top-level type is Asset or Liability. Filters CompanyId
    /// explicitly (defense in depth alongside the global tenant filter).
    /// </summary>
    internal static async Task<bool> IsValidMoneyAccountAsync(IUnitOfWork unitOfWork, int? accountId, int companyId)
    {
        if (accountId == null) return false;
        var account = await unitOfWork.Accounts.FirstOrDefaultAsync(
            a => a.Id == accountId.Value && a.CompanyId == companyId && a.IsActive);
        return account != null
            && (account.AccountType == AccountType.Asset || account.AccountType == AccountType.Liability);
    }
}
