import { AuthError } from '@/lib/auth/session';
import { getActiveOptionsByCategory } from '@/features/foundation/master-options/service';
import type { FoundationBranch } from './types';

function mapBranchOption(
  option: Awaited<ReturnType<typeof getActiveOptionsByCategory>>[number]
): FoundationBranch {
  return {
    id: option.id,
    code: option.code,
    name: option.label,
    value: option.value
  };
}

export async function getUserBranches(): Promise<FoundationBranch[]> {
  const options = await getActiveOptionsByCategory('crm_branch');

  return options.map(mapBranchOption);
}

export async function getActiveBranch(): Promise<FoundationBranch | null> {
  const branches = await getUserBranches();

  if (branches.length === 1) {
    return branches[0];
  }

  return null;
}

export async function validateBranchAccess(branchId?: string | null) {
  if (!branchId) {
    return getActiveBranch();
  }

  const branches = await getUserBranches();
  const branch = branches.find((item) => item.id === branchId);

  if (!branch) {
    throw new AuthError('Branch access denied', 403);
  }

  return branch;
}
