import { getActiveOptionsByCategory } from '@/features/foundation/master-options/service';
import { AuthError } from '@/lib/auth/session';
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(organizationId?: string): Promise<FoundationBranch[]> {
  const options = await getActiveOptionsByCategory(
    'crm_branch',
    organizationId ? { organizationId } : undefined
  );

  return options.map(mapBranchOption);
}

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

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

  return null;
}

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

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

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

  return branch;
}
