import { Injectable } from "@nestjs/common";
import { Product } from "../../../products/entities/product.entity";
import { Repository } from "typeorm";
import { InjectRepository } from "@nestjs/typeorm";
import { Category } from "../../../category/entities/category.entity";
import { FileEntity } from "../../../files/entities/file.entity";
import { Brand } from "../../../brands/entities/brand.entity";
import { ProductStatus } from "../../../products/enums";
import { faker } from "@faker-js/faker";

@Injectable()
export class ProductSeedService {
    constructor(@InjectRepository(Product) private productRepository: Repository<Product>
    ) { }
    async run(categories: Partial<Category>[], brands: Partial<Brand>[]) {
        console.log("Seeding products ...");

        await this.productRepository.delete({});
        const products: Product[] = [];
        const imageCategories = ["semiconductor", "powerconnector", "transistor",
            "microswitch", "DCMotor", "motherboard"];
        for (let i = 0; i < 100; i++) {
            const images: Partial<FileEntity>[] = [];
            for (let j = 0; j < 3; j++) {
                images.push({
                    //use multiple image categories to get more diverse images
                    path: faker.image.urlLoremFlickr({
                        category: imageCategories[Math.floor(Math.random() * imageCategories.length)]
                    })
                });
            }
            const product: Product = {
                name: "product " + i,
                description: "product description " + i,
                price: Math.floor(Math.random() * 1000000),
                images,
                category:
                    categories[Math.floor(Math.random() * categories.length)]?.subCategories?.[0]?.id
                    || categories[Math.floor(Math.random() * categories.length)],
                brand: { name: brands[Math.floor(Math.random() * brands.length)].name },
                quantity: Math.floor(Math.random() * 100),
                status: Object.values(ProductStatus)
                [Math.floor(Math.random() * Object.values(ProductStatus).length)],
                createdBy: { id: 1 },
            };
            products.push(product);
        }
        await this.productRepository.save(products);

        console.log("Seeding products completed");
    }
}