import { faker } from '@faker-js/faker';

import { Product } from "./product.enum";
import { dateToOrdinal } from './ordinalDate';

export type Barcode = string;

export type ParsedBarcode = {
    product: Product;
    date: string;
    processor: string;
    weight: number;
};

export const barcodeToProduct = (barcode: Barcode): ParsedBarcode => {
    const [ , productCode, date, processor, weight ] = barcode.match(/^(\d{5})(\d{5})(\d{2})(\d{4})$/) || [];
    const product = Object.entries(Product).find(([k, v]) => v === productCode);

    if (!product) {
        throw new Error(`Invalid barcode: ${barcode}`);
    }

    return {
        product: product[0] as Product,
        date: date,
        processor,
        weight: parseInt(weight) / 100,
    };
};

export const generateRandomBarcode = (): Barcode => {
    const product = faker.helpers.enumValue(Product);
    const date = dateToOrdinal(new Date(faker.date.recent({ days: 30 })));
    const processor = faker.number.int({ min: 11, max: 17 });
    const weight = faker.number.int({ min: 1000, max: 1999 });
    return `${product}${date}${processor}${weight}`;
};
