export type PackageWithLocationAvailability = {
    id: number;
    location_ids: number[];
};

export function packageAvailableAtLocation(
    pkg: PackageWithLocationAvailability,
    locationId: number | '' | null | undefined,
    serviceType: 'fixed' | 'mobile',
): boolean {
    if (pkg.location_ids.length === 0) {
        return true;
    }

    if (serviceType === 'mobile') {
        return false;
    }

    if (locationId === '' || locationId === null || locationId === undefined) {
        return false;
    }

    return pkg.location_ids.includes(Number(locationId));
}

export function packagesForLocation<T extends PackageWithLocationAvailability>(
    packages: T[],
    locationId: number | '' | null | undefined,
    serviceType: 'fixed' | 'mobile',
): T[] {
    return packages.filter((pkg) =>
        packageAvailableAtLocation(pkg, locationId, serviceType),
    );
}

export function resolvePackageIdAfterLocationChange(
    packages: PackageWithLocationAvailability[],
    locationId: number | '' | null | undefined,
    serviceType: 'fixed' | 'mobile',
    currentPackageId: number | '',
): number | '' {
    if (currentPackageId === '') {
        return '';
    }

    const available = packagesForLocation(
        packages,
        locationId,
        serviceType,
    );

    return available.some((pkg) => pkg.id === currentPackageId)
        ? currentPackageId
        : '';
}
