import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Product } from '../entities/product.entity';

@Injectable()
export class ProductService {
  constructor(
    @InjectRepository(Product)
    private productRepository: Repository<Product>,
  ) {}

  async findAll() {
    return this.productRepository.find();
  }

  async findOne(id: string) {
    return this.productRepository.findOne({ where: { id: parseInt(id) } });
  }

  async create(createProductDto: any) {
    const product = this.productRepository.create(createProductDto);
    return this.productRepository.save(product);
  }

  async update(id: string, updateProductDto: any) {
    await this.productRepository.update(id, updateProductDto);
    return this.findOne(id);
  }

  async remove(id: string) {
    const product = await this.findOne(id);
    return this.productRepository.remove(product);
  }

  async findByCategory(category: string) {
    return this.productRepository.find({ where: { category } });
  }

  async search(term: string) {
    return this.productRepository
      .createQueryBuilder('product')
      .where('product.name ILIKE :term OR product.description ILIKE :term', { term: `%${term}%` })
      .getMany();
  }

  async findPublicProducts(query?: any) {
    // Return products that are marked as public/featured
    return this.productRepository.find({ 
      where: { isPublic: true },
      take: query?.limit || 10 
    });
  }

  async findFeaturedProducts() {
    // Return featured products
    return this.productRepository.find({ 
      where: { isFeatured: true },
      take: 6 
    });
  }

  async getCategories() {
    // Return unique product categories
    const categories = await this.productRepository
      .createQueryBuilder('product')
      .select('DISTINCT product.category', 'category')
      .getRawMany();
    
    return categories.map(cat => cat.category);
  }
} 