import { Router } from 'express';
import { DataSource } from 'typeorm';
import { ProductsService } from './services';
import { ProductsController, CategoriesController } from './controllers';
import { Product, ProductCategory, ProductAttribute, ProductAttributeValue, ProductVariant } from './entities';

export interface ProductsModuleOptions {
  dataSource: DataSource;
  basePath?: string;
}

export class ProductsModule {
  public router: Router;
  public productsService: ProductsService;
  private dataSource: DataSource;
  private basePath: string;

  constructor(options: ProductsModuleOptions) {
    this.dataSource = options.dataSource;
    this.basePath = options.basePath || '';
    this.router = Router();
    this.initializeServices();
    this.initializeRoutes();
  }

  private initializeServices(): void {
    const productRepository = this.dataSource.getRepository(Product);
    const categoryRepository = this.dataSource.getRepository(ProductCategory);

    this.productsService = new ProductsService(productRepository, categoryRepository);
  }

  private initializeRoutes(): void {
    const productsController = new ProductsController(this.productsService);
    const categoriesController = new CategoriesController(this.productsService);

    this.router.use(`${this.basePath}/products`, productsController.router);
    this.router.use(`${this.basePath}/categories`, categoriesController.router);
  }

  static getEntities(): Function[] {
    return [Product, ProductCategory, ProductAttribute, ProductAttributeValue, ProductVariant];
  }
}
